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