From 7a33837ed7cc91720ce4419aae3dfb771777e503 Mon Sep 17 00:00:00 2001 From: Hajime Hoshi Date: Fri, 25 Mar 2022 20:46:59 +0900 Subject: [PATCH] audio: change the type of SetBufferSize to time.Duration Updates #2026 --- audio/audio.go | 2 +- audio/player.go | 8 +++++--- examples/realtimepcm/main.go | 5 +++-- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/audio/audio.go b/audio/audio.go index aaa52f385..ff8feae8e 100644 --- a/audio/audio.go +++ b/audio/audio.go @@ -403,7 +403,7 @@ func (p *Player) SetVolume(volume float64) { // If 0 is specified, the default buffer size is used. // A small buffer size is useful if you want to play a real-time PCM for example. // Note that the audio quality might be affected if you modify the buffer size. -func (p *Player) SetBufferSize(bufferSize int) { +func (p *Player) SetBufferSize(bufferSize time.Duration) { p.p.SetBufferSize(bufferSize) } diff --git a/audio/player.go b/audio/player.go index bc462f703..cef0284c4 100644 --- a/audio/player.go +++ b/audio/player.go @@ -286,15 +286,17 @@ func (p *playerImpl) Err() error { return p.player.Err() } -func (p *playerImpl) SetBufferSize(bufferSize int) { +func (p *playerImpl) SetBufferSize(bufferSize time.Duration) { p.m.Lock() defer p.m.Unlock() + bufferSizeInBytes := int(bufferSize * bytesPerSample * time.Duration(p.factory.sampleRate) / time.Second) + bufferSizeInBytes = bufferSizeInBytes / bytesPerSample * bytesPerSample if p.player == nil { - p.initBufferSize = bufferSize + p.initBufferSize = bufferSizeInBytes return } - p.player.SetBufferSize(bufferSize) + p.player.SetBufferSize(bufferSizeInBytes) } func (p *playerImpl) source() io.Reader { diff --git a/examples/realtimepcm/main.go b/examples/realtimepcm/main.go index 5900ecfe3..052466e60 100644 --- a/examples/realtimepcm/main.go +++ b/examples/realtimepcm/main.go @@ -21,6 +21,7 @@ import ( "log" "math" "sync" + "time" "github.com/hajimehoshi/ebiten/v2" "github.com/hajimehoshi/ebiten/v2/audio" @@ -135,8 +136,8 @@ func (g *Game) Update() error { // Adjust the buffer size to reflect the audio source changes in real time. // Note that Ebiten doesn't guarantee the audio quality when the buffer size is modified. - // 8192 should work in most cases, but this might cause glitches in some environments. - g.player.SetBufferSize(8192) + // 1/20[s] should work in most cases, but this might cause glitches in some environments. + g.player.SetBufferSize(time.Second / 20) } g.sineWave.Update(ebiten.IsKeyPressed(ebiten.KeyA)) return nil