From 13b0d82b6d74c7fd61338ae98c9dba6faaa4e705 Mon Sep 17 00:00:00 2001 From: Hajime Hoshi Date: Sun, 27 Jan 2019 00:31:55 +0900 Subject: [PATCH] audio: Use oto.NewContext --- audio/audio.go | 36 +++++++++++++++++++---- audio/{driver_test.go => context_test.go} | 23 ++++++++++++--- 2 files changed, 49 insertions(+), 10 deletions(-) rename audio/{driver_test.go => context_test.go} (66%) diff --git a/audio/audio.go b/audio/audio.go index 91c213f40..dd588cf1b 100644 --- a/audio/audio.go +++ b/audio/audio.go @@ -103,13 +103,34 @@ func CurrentContext() *Context { return c } -var driverForTesting io.WriteCloser +type context interface { + NewPlayer() io.WriteCloser + io.Closer +} -func newDriver(sampleRate int) (io.WriteCloser, error) { - if driverForTesting != nil { - return driverForTesting, nil +var contextForTesting context + +type otoContext struct { + c *oto.Context +} + +func (d *otoContext) NewPlayer() io.WriteCloser { + return d.c.NewPlayer() +} + +func (d *otoContext) Close() error { + return d.c.Close() +} + +func newContext(sampleRate int) (context, error) { + if contextForTesting != nil { + return contextForTesting, nil } - return oto.NewPlayer(sampleRate, channelNum, bytesPerSample/channelNum, bufferSize()) + c, err := oto.NewContext(sampleRate, channelNum, bytesPerSample/channelNum, bufferSize()) + if err != nil { + return nil, err + } + return &otoContext{c}, nil } func (c *Context) loop() { @@ -147,11 +168,14 @@ func (c *Context) loop() { // e.g. a variable for JVM on Android might not be set. <-initCh - p, err := newDriver(c.sampleRate) + context, err := newContext(c.sampleRate) if err != nil { c.err = err return } + defer context.Close() + + p := context.NewPlayer() defer p.Close() for { diff --git a/audio/driver_test.go b/audio/context_test.go similarity index 66% rename from audio/driver_test.go rename to audio/context_test.go index 17fc28bdb..c302433dd 100644 --- a/audio/driver_test.go +++ b/audio/context_test.go @@ -14,16 +14,31 @@ package audio -type dummyDriver struct{} +import ( + "io" +) -func (d *dummyDriver) Write(b []byte) (int, error) { +type ( + dummyContext struct{} + dummyPlayer struct{} +) + +func (d *dummyContext) NewPlayer() io.WriteCloser { + return &dummyPlayer{} +} + +func (d *dummyContext) Close() error { + return nil +} + +func (p *dummyPlayer) Write(b []byte) (int, error) { return len(b), nil } -func (d *dummyDriver) Close() error { +func (p *dummyPlayer) Close() error { return nil } func init() { - driverForTesting = &dummyDriver{} + contextForTesting = &dummyContext{} }