Skip to content

Commit

Permalink
Tweak the speaker's context & player's buffer sizes
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkKremer committed Nov 9, 2023
1 parent 624d285 commit 3de5607
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions speaker/speaker.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@
package speaker

import (
"github.com/ebitengine/oto/v3"
"github.com/gopxl/beep"
"github.com/pkg/errors"
"io"
"sync"

"github.com/ebitengine/oto/v3"
"github.com/pkg/errors"

"github.com/gopxl/beep"
)

const channelCount = 2
Expand All @@ -33,21 +35,29 @@ func Init(sampleRate beep.SampleRate, bufferSize int) error {

mixer = beep.Mixer{}

// We split the total amount of buffer size between the driver and the player.
// This seems to be a decent ratio on my machine, but it may have different
// results on other OS's because of different underlying implementations.
// Both buffers try to keep themselves filled, so the total buffered
// number of samples should be some number less than bufferSize.
driverBufferSize := bufferSize / 2
playerBufferSize := bufferSize / 2

var err error
var readyChan chan struct{}
context, readyChan, err := oto.NewContext(&oto.NewContextOptions{
SampleRate: int(sampleRate),
ChannelCount: channelCount,
Format: otoFormat,
BufferSize: 0, // use the default
BufferSize: sampleRate.D(driverBufferSize),
})
if err != nil {
return errors.Wrap(err, "failed to initialize speaker")
}
<-readyChan

player = context.NewPlayer(newReaderFromStreamer(&mixer))
player.SetBufferSize(bufferSize * bytesPerSample)
player.SetBufferSize(playerBufferSize * bytesPerSample)
player.Play()

return nil
Expand Down

0 comments on commit 3de5607

Please sign in to comment.