From fe55e55b7e856d679d2c825c827b801baab71d0d Mon Sep 17 00:00:00 2001 From: Hajime Hoshi Date: Sat, 27 Apr 2019 22:30:09 +0900 Subject: [PATCH] audio: Refactoring --- audio/audio.go | 34 ++++++++++++++++------------------ audio/context.go | 13 +++++++++++-- 2 files changed, 27 insertions(+), 20 deletions(-) diff --git a/audio/audio.go b/audio/audio.go index 7b0da7b3b..7dca1d557 100644 --- a/audio/audio.go +++ b/audio/audio.go @@ -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() diff --git a/audio/context.go b/audio/context.go index 69d9dd899..39fc3aea2 100644 --- a/audio/context.go +++ b/audio/context.go @@ -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, } }