audio: Use a boolean value to inidicate inited state intead 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:45:37 +09:00
parent fe55e55b7e
commit 14b6e95217

View File

@ -50,11 +50,11 @@ import (
// For a typical usage example, see examples/wav/main.go. // For a typical usage example, see examples/wav/main.go.
type Context struct { type Context struct {
c context c context
initCh chan struct{}
mux *mux mux *mux
sampleRate int sampleRate int
err error err error
inited bool
suspended bool suspended bool
ready bool ready bool
@ -88,7 +88,6 @@ func NewContext(sampleRate int) (*Context, error) {
c := &Context{ c := &Context{
sampleRate: sampleRate, sampleRate: sampleRate,
c: newContext(sampleRate), c: newContext(sampleRate),
initCh: make(chan struct{}),
} }
theContext = c theContext = c
c.mux = newMux() c.mux = newMux()
@ -105,11 +104,10 @@ func NewContext(sampleRate int) (*Context, error) {
c.m.Unlock() c.m.Unlock()
}) })
var once sync.Once
h.AppendHookOnBeforeUpdate(func() error { h.AppendHookOnBeforeUpdate(func() error {
once.Do(func() { c.m.Lock()
close(c.initCh) c.inited = true
}) c.m.Unlock()
var err error var err error
theContextLock.Lock() theContextLock.Lock()
@ -135,19 +133,22 @@ func CurrentContext() *Context {
return c return c
} }
func (c *Context) loop() { func (c *Context) playable() bool {
<-c.initCh c.m.Lock()
i := c.inited
s := c.suspended
c.m.Unlock()
return i && !s
}
func (c *Context) loop() {
defer c.c.Close() defer c.c.Close()
p := c.c.NewPlayer() p := c.c.NewPlayer()
defer p.Close() defer p.Close()
for { for {
c.m.Lock() if !c.playable() {
s := c.suspended
c.m.Unlock()
if s {
runtime.Gosched() runtime.Gosched()
continue continue
} }