audio: Use a boolean value to indicate suspending state instead of channels

This is a preparation to use oto.Players for Players. By using a
boolean value, suspending state can be detected from multiple
oto.Players.
This commit is contained in:
Hajime Hoshi 2019-04-27 22:00:12 +09:00
parent 2b7705e7ad
commit 1327e2239c

View File

@ -55,6 +55,7 @@ type Context struct {
mux *mux mux *mux
sampleRate int sampleRate int
err error err error
suspended bool
ready bool ready bool
m sync.Mutex m sync.Mutex
@ -108,14 +109,16 @@ func CurrentContext() *Context {
} }
func (c *Context) loop() { func (c *Context) loop() {
suspendCh := make(chan struct{}, 1)
resumeCh := make(chan struct{}, 1)
h := getHook() h := getHook()
h.OnSuspendAudio(func() { h.OnSuspendAudio(func() {
suspendCh <- struct{}{} c.m.Lock()
c.suspended = true
c.m.Unlock()
}) })
h.OnResumeAudio(func() { h.OnResumeAudio(func() {
resumeCh <- struct{}{} c.m.Lock()
c.suspended = false
c.m.Unlock()
}) })
var once sync.Once var once sync.Once
@ -143,10 +146,13 @@ func (c *Context) loop() {
defer p.Close() defer p.Close()
for { for {
select { c.m.Lock()
case <-suspendCh: s := c.suspended
<-resumeCh c.m.Unlock()
default: if s {
runtime.Gosched()
continue
}
if _, err := io.CopyN(p, c.mux, 2048); err != nil { if _, err := io.CopyN(p, c.mux, 2048); err != nil {
c.m.Lock() c.m.Lock()
c.err = err c.err = err
@ -157,7 +163,6 @@ func (c *Context) loop() {
c.ready = true c.ready = true
c.m.Unlock() c.m.Unlock()
} }
}
} }
// IsReady returns a boolean value indicating whether the audio is ready or not. // IsReady returns a boolean value indicating whether the audio is ready or not.