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,20 +146,22 @@ 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 {
if _, err := io.CopyN(p, c.mux, 2048); err != nil { runtime.Gosched()
c.m.Lock() continue
c.err = err
c.m.Unlock()
return
}
c.m.Lock()
c.ready = true
c.m.Unlock()
} }
if _, err := io.CopyN(p, c.mux, 2048); err != nil {
c.m.Lock()
c.err = err
c.m.Unlock()
return
}
c.m.Lock()
c.ready = true
c.m.Unlock()
} }
} }