audio: Refactoring

This commit is contained in:
Hajime Hoshi 2019-04-27 22:30:09 +09:00
parent 1327e2239c
commit fe55e55b7e
2 changed files with 27 additions and 20 deletions

View File

@ -85,30 +85,14 @@ func NewContext(sampleRate int) (*Context, error) {
panic("audio: context is already created") panic("audio: context is already created")
} }
ch := make(chan struct{})
c := &Context{ c := &Context{
sampleRate: sampleRate, sampleRate: sampleRate,
c: newContext(sampleRate, ch), c: newContext(sampleRate),
initCh: ch, initCh: make(chan struct{}),
} }
theContext = c theContext = c
c.mux = newMux() c.mux = newMux()
go c.loop()
return c, nil
}
// CurrentContext returns the current context or nil if there is no context.
func CurrentContext() *Context {
theContextLock.Lock()
c := theContext
theContextLock.Unlock()
return c
}
func (c *Context) loop() {
h := getHook() h := getHook()
h.OnSuspendAudio(func() { h.OnSuspendAudio(func() {
c.m.Lock() c.m.Lock()
@ -138,6 +122,20 @@ func (c *Context) loop() {
return err return err
}) })
go c.loop()
return c, nil
}
// CurrentContext returns the current context or nil if there is no context.
func CurrentContext() *Context {
theContextLock.Lock()
c := theContext
theContextLock.Unlock()
return c
}
func (c *Context) loop() {
<-c.initCh <-c.initCh
defer c.c.Close() defer c.c.Close()

View File

@ -93,13 +93,22 @@ func (p *otoPlayer) ensurePlayer() error {
return nil return nil
} }
func newContext(sampleRate int, initCh <-chan struct{}) context { func newContext(sampleRate int) context {
if contextForTesting != nil { if contextForTesting != nil {
return contextForTesting return contextForTesting
} }
ch := make(chan struct{})
var once sync.Once
hooks.AppendHookOnBeforeUpdate(func() error {
once.Do(func() {
close(ch)
})
return nil
})
return &otoContext{ return &otoContext{
sampleRate: sampleRate, sampleRate: sampleRate,
initCh: initCh, initCh: ch,
} }
} }