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")
}
ch := make(chan struct{})
c := &Context{
sampleRate: sampleRate,
c: newContext(sampleRate, ch),
initCh: ch,
c: newContext(sampleRate),
initCh: make(chan struct{}),
}
theContext = c
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.OnSuspendAudio(func() {
c.m.Lock()
@ -138,6 +122,20 @@ func (c *Context) loop() {
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
defer c.c.Close()

View File

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