From 29eade9b4a79f23637597af88cdee9b8e2e44eea Mon Sep 17 00:00:00 2001 From: Hajime Hoshi Date: Tue, 4 May 2021 18:49:34 +0900 Subject: [PATCH] audio/internal/readdriver: Bug fix: Implement Suspend/Resume for browsers Closes #1630 --- audio/audio.go | 6 ++++++ audio/internal/readerdriver/driver.go | 2 ++ audio/internal/readerdriver/driver_js.go | 16 ++++++++++++++++ audio/readerplayer.go | 14 ++++++++++++++ 4 files changed, 38 insertions(+) diff --git a/audio/audio.go b/audio/audio.go index 62bb75bf8..2fd5c60ed 100644 --- a/audio/audio.go +++ b/audio/audio.go @@ -127,9 +127,15 @@ func NewContext(sampleRate int) *Context { h := getHook() h.OnSuspendAudio(func() { c.semaphore <- struct{}{} + if s, ok := np.(interface{ suspend() }); ok { + s.suspend() + } }) h.OnResumeAudio(func() { <-c.semaphore + if s, ok := np.(interface{ resume() }); ok { + s.resume() + } }) h.AppendHookOnBeforeUpdate(func() error { diff --git a/audio/internal/readerdriver/driver.go b/audio/internal/readerdriver/driver.go index e0d2198c4..e29509832 100644 --- a/audio/internal/readerdriver/driver.go +++ b/audio/internal/readerdriver/driver.go @@ -21,6 +21,8 @@ import ( type Context interface { NewPlayer(io.Reader) Player MaxBufferSize() int + Suspend() + Resume() io.Closer } diff --git a/audio/internal/readerdriver/driver_js.go b/audio/internal/readerdriver/driver_js.go index 94d468ef7..7af48e1ef 100644 --- a/audio/internal/readerdriver/driver_js.go +++ b/audio/internal/readerdriver/driver_js.go @@ -139,6 +139,14 @@ func (c *context) MaxBufferSize() int { return c.oneBufferSize() * 2 } +func (c *context) Suspend() { + c.audioContext.Call("suspend") +} + +func (c *context) Resume() { + c.audioContext.Call("resume") +} + func (p *player) Pause() { if p.state != playerPlay { return @@ -299,6 +307,14 @@ func (w *go2cppDriverWrapper) MaxBufferSize() int { return w.c.MaxBufferSize() } +func (w *go2cppDriverWrapper) Suspend() { + // Do nothing so far. +} + +func (w *go2cppDriverWrapper) Resume() { + // Do nothing so far. +} + func (w *go2cppDriverWrapper) Close() error { return w.c.Close() } diff --git a/audio/readerplayer.go b/audio/readerplayer.go index 8ba91ace0..da21d98fe 100644 --- a/audio/readerplayer.go +++ b/audio/readerplayer.go @@ -60,6 +60,20 @@ func (f *readerPlayerFactory) newPlayerImpl(context *Context, src io.Reader) (pl return p, nil } +func (f *readerPlayerFactory) suspend() { + if f.context == nil { + return + } + f.context.Suspend() +} + +func (f *readerPlayerFactory) resume() { + if f.context == nil { + return + } + f.context.Resume() +} + func (p *readerPlayer) ensurePlayer() error { // Initialize the underlying player lazily to enable calling NewContext in an 'init' function. // Accessing the underlying player functions requires the environment to be already initialized,