Skip to content

Commit

Permalink
set audio buffer size explicitly
Browse files Browse the repository at this point in the history
  • Loading branch information
ichirin2501 committed Jan 15, 2024
1 parent b1b3953 commit 63c5b9b
Showing 1 changed file with 21 additions and 11 deletions.
32 changes: 21 additions & 11 deletions cmd/rgnes/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,30 +58,40 @@ func (r *renderer) Refresh() {

// ref: https://github.com/fogleman/nes/blob/3880f3400500b1ff2e89af4e12e90be46c73ae07/ui/audio.go#L5
type Player struct {
stream *portaudio.Stream
sampleRate float64
outputChannels int
channel chan float32
stream *portaudio.Stream
sampleRate float64
channel chan float32
}

func newPlayer() (*Player, error) {
host, err := portaudio.DefaultHostApi()
if err != nil {
return nil, err
}
parameters := portaudio.HighLatencyParameters(nil, host.DefaultOutputDevice)
outputChannels := 2
if host.DefaultOutputDevice.MaxOutputChannels < 2 {
outputChannels = host.DefaultOutputDevice.MaxOutputChannels
}
sampleRate := 48000.0
if host.DefaultOutputDevice.DefaultSampleRate < sampleRate {
sampleRate = host.DefaultOutputDevice.DefaultSampleRate

}
// This value was roughly determined.
// In the current implementation, if this value is too small or too large, the sound will be unexpected.
framesPerBuffer := 256

p := Player{
sampleRate: parameters.SampleRate,
outputChannels: parameters.Output.Channels,
// If this channel size is too large (e.g. 44100), the BGM will be delayed. Make the size not too big
channel: make(chan float32, 3000),
sampleRate: sampleRate,
// This value was roughly determind too.
// In the current implementation, if this channel size is too large (e.g. 44100), the sound will be delayed.
channel: make(chan float32, 2048),
}

cbFunc := func(out []float32) {
var output float32
for i := range out {
if i%p.outputChannels == 0 {
if i%outputChannels == 0 {
select {
case sample := <-p.channel:
output = sample
Expand All @@ -92,7 +102,7 @@ func newPlayer() (*Player, error) {
out[i] = output
}
}
stream, err := portaudio.OpenStream(parameters, cbFunc)
stream, err := portaudio.OpenDefaultStream(0, outputChannels, sampleRate, framesPerBuffer, cbFunc)
if err != nil {
return nil, err
}
Expand Down

0 comments on commit 63c5b9b

Please sign in to comment.