/
state.go
121 lines (102 loc) · 2.11 KB
/
state.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
package player
import (
"fmt"
"sync"
)
// State stores the various state of the player. It is also used by the queue
// to determine some actions related to currently playing tracks.
type State struct {
sync.RWMutex
Playing bool
Stopped bool
Paused bool
Volume int
}
// NewPlayerState will return a new player state
func NewState() *State {
return &State{
Volume: 256, // 256 is the normal volume
}
}
func (p *Player) Playing() bool {
p.state.RLock()
defer p.state.RUnlock()
return p.state.Playing
}
func (p *Player) Stopped() bool {
p.state.RLock()
defer p.state.RUnlock()
return p.state.Stopped
}
func (p *Player) Paused() bool {
p.state.RLock()
defer p.state.RUnlock()
return p.state.Paused
}
func (p *Player) Volume() int {
p.state.RLock()
defer p.state.RUnlock()
return p.state.Volume
}
// Stop will immediately stop the player
func (p *Player) Stop() {
p.state.Lock()
defer p.state.Unlock()
if !p.state.Playing {
return
}
p.state.Stopped = true
p.stop <- true
}
// Pause will pause an ongoing stream
func (p *Player) Pause() {
p.state.Lock()
defer p.state.Unlock()
if p.stream == nil || !p.state.Playing {
return
}
p.state.Paused = true
p.stream.SetPaused(true)
}
// Skip will skip the currently playing track
func (p *Player) Skip() {
p.state.Lock()
defer p.state.Unlock()
if !p.state.Playing {
return
}
p.stop <- true
}
// Resume will resume a paused stream
func (p *Player) Resume() {
p.state.Lock()
defer p.state.Unlock()
if p.stream == nil || !p.state.Paused {
return
}
p.state.Paused = false
p.stream.SetPaused(false)
}
// SetVolume will set the volume for the next track
func (p *Player) SetVolume(v int) error {
p.state.Lock()
defer p.state.Unlock()
// Invalid values
if v < 0 || v > 512 {
return fmt.Errorf("invalid volume value")
}
p.state.Volume = v
return nil
}
func (p *Player) SetVolumePercent(v int) error {
p.state.Lock()
defer p.state.Unlock()
if v < 0 || v > 200 {
return fmt.Errorf("invalid volume percentage")
}
vol := 256 * v / 100
if err := p.SetVolume(vol); err != nil {
return fmt.Errorf("unable to set volume: %w", err)
}
return nil
}