From 305016f636541164b2bfb1ab6d89b1b6b8ae46a7 Mon Sep 17 00:00:00 2001 From: Hajime Hoshi Date: Sun, 13 Mar 2016 03:33:02 +0900 Subject: [PATCH] audio: Reduce magic numbers --- exp/audio/audio.go | 9 +++++++-- exp/audio/audio_js.go | 6 ++---- exp/audio/audio_windows.go | 6 ++---- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/exp/audio/audio.go b/exp/audio/audio.go index 2d5c356b5..5c9602c58 100644 --- a/exp/audio/audio.go +++ b/exp/audio/audio.go @@ -21,7 +21,6 @@ import ( "time" ) -// TODO: In JavaScript, mixing should be done by WebAudio for performance. type mixedPlayersStream struct { context *Context writtenBytes int @@ -34,12 +33,18 @@ func min(a, b int) int { return b } +const ( + channelNum = 2 + bytesPerSample = 2 + bitsPerSample = bytesPerSample * 8 +) + func (s *mixedPlayersStream) Read(b []byte) (int, error) { s.context.Lock() defer s.context.Unlock() // TODO: 60 (FPS) is a magic number - bytesPerFrame := s.context.sampleRate * 4 / 60 + bytesPerFrame := s.context.sampleRate * bytesPerSample * channelNum / 60 x := s.context.frames*bytesPerFrame + len(b) if x <= s.writtenBytes { return 0, nil diff --git a/exp/audio/audio_js.go b/exp/audio/audio_js.go index 6a04dbf8d..02e95da87 100644 --- a/exp/audio/audio_js.go +++ b/exp/audio/audio_js.go @@ -75,9 +75,7 @@ func max64(a, b int64) int64 { } func (p *player) proceed() error { - const channelNum = 2 - const bytesPerSample = channelNum * 16 / 8 - bufferSize := p.sampleRate * bytesPerSample / 60 + bufferSize := p.sampleRate * bytesPerSample * channelNum / 60 c := int64(p.context.Get("currentTime").Float() * float64(p.sampleRate)) if p.positionInSamples < c { p.positionInSamples = c @@ -85,7 +83,7 @@ func (p *player) proceed() error { b := make([]byte, bufferSize) n, err := p.src.Read(b) if 0 < n { - buf := p.context.Call("createBuffer", channelNum, n/bytesPerSample, p.sampleRate) + buf := p.context.Call("createBuffer", channelNum, n/bytesPerSample/channelNum, p.sampleRate) l := buf.Call("getChannelData", 0) r := buf.Call("getChannelData", 1) il, ir := toLR(b[:n]) diff --git a/exp/audio/audio_windows.go b/exp/audio/audio_windows.go index 86b44d75d..0229813b0 100644 --- a/exp/audio/audio_windows.go +++ b/exp/audio/audio_windows.go @@ -78,12 +78,10 @@ type player struct { } func startPlaying(src io.Reader, sampleRate int) (*player, error) { - const numChannels = 2 - const bitsPerSample = 16 - const numBlockAlign = numChannels * bitsPerSample / 8 + const numBlockAlign = channelNum * bitsPerSample / 8 f := C.WAVEFORMATEX{ wFormatTag: C.WAVE_FORMAT_PCM, - nChannels: numChannels, + nChannels: channelNum, nSamplesPerSec: C.DWORD(sampleRate), nAvgBytesPerSec: C.DWORD(sampleRate) * numBlockAlign, wBitsPerSample: bitsPerSample,