audio: change the type of SetBufferSize to time.Duration

Updates #2026
This commit is contained in:
Hajime Hoshi 2022-03-25 20:46:59 +09:00
parent 0e8c423e51
commit 7a33837ed7
3 changed files with 9 additions and 6 deletions

View File

@ -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)
}

View File

@ -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 {

View File

@ -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