audio: Reduce magic numbers

This commit is contained in:
Hajime Hoshi 2016-03-13 03:33:02 +09:00
parent 8c065a28e1
commit 305016f636
3 changed files with 11 additions and 10 deletions

View File

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

View File

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

View File

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