-
Notifications
You must be signed in to change notification settings - Fork 1
/
player.go
131 lines (112 loc) · 2.38 KB
/
player.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package audio
import (
"io"
"sync"
"github.com/disgoorg/audio/pcm"
"github.com/disgoorg/disgo/voice"
)
type Player interface {
voice.OpusFrameProvider
Volume() float32
SetVolume(volume float32)
Paused() bool
SetPaused(paused bool)
}
func NewPlayer(providerFunc func() pcm.FrameProvider, listeners ...Listener) (Player, error) {
player := &defaultPlayer{
listeners: listeners,
volume: 1,
paused: false,
}
pauseableProvider := pcm.NewPauseablePCMFrameProvider(pcm.NewVariablePCMFrameProvider(providerFunc), func() bool {
return player.paused
})
volumeProvider := pcm.NewPCMVolumeFrameProvider(pauseableProvider, func() float32 {
return player.volume
})
var err error
if player.opusFrameProvider, err = pcm.NewOpusProvider(nil, volumeProvider); err != nil {
return nil, err
}
return player, nil
}
type defaultPlayer struct {
opusFrameProvider voice.OpusFrameProvider
volume float32
paused bool
playing bool
mu sync.Mutex
listeners []Listener
}
func (p *defaultPlayer) Volume() float32 {
p.mu.Lock()
defer p.mu.Unlock()
return p.volume
}
func (p *defaultPlayer) SetVolume(volume float32) {
p.mu.Lock()
defer p.mu.Unlock()
p.volume = volume
}
func (p *defaultPlayer) Paused() bool {
p.mu.Lock()
defer p.mu.Unlock()
return p.paused
}
func (p *defaultPlayer) SetPaused(paused bool) {
p.mu.Lock()
if p.paused == paused {
p.mu.Unlock()
return
}
p.paused = paused
p.mu.Unlock()
if paused {
p.emit(func(l Listener) {
l.OnPause(p)
})
} else {
p.emit(func(l Listener) {
l.OnResume(p)
})
}
}
func (p *defaultPlayer) ProvideOpusFrame() ([]byte, error) {
frame, err := p.opusFrameProvider.ProvideOpusFrame()
if err == io.EOF {
p.playing = false
p.emit(func(l Listener) {
l.OnEnd(p)
})
} else if err != nil {
p.emit(func(l Listener) {
l.OnError(p, err)
})
}
if frame != nil && !p.playing {
p.playing = true
p.emit(func(l Listener) {
l.OnStart(p)
})
}
return frame, err
}
func (p *defaultPlayer) Close() {
p.opusFrameProvider.Close()
p.emit(func(l Listener) {
l.OnClose(p)
})
}
func (p *defaultPlayer) emit(l func(l Listener)) {
for _, listener := range p.listeners {
l(listener)
}
}
type Listener interface {
OnPause(player Player)
OnResume(player Player)
OnStart(player Player)
OnEnd(player Player)
OnError(player Player, err error)
OnClose(player Player)
}