audio: Add comments, add IsPlaying

This commit is contained in:
Hajime Hoshi 2015-01-24 21:46:30 +09:00
parent 2c7430171d
commit 2d5ac9e987
4 changed files with 21 additions and 23 deletions

View File

@ -62,7 +62,7 @@ func square(out []float32, volume float64, freq float64, sequence float64) {
for i := 0; i < len(out); i++ {
a := float32(volume)
if i%length < int(float64(length)*sequence) {
a = 0
a = -a
}
out[i] = a
}

View File

@ -46,9 +46,7 @@ func Queue(channel int, l []float32, r []float32) {
audio.Queue(channel, l, r)
}
// TODO: Add funciton to append samples to the buffer without adjusting.
// TODO: better name
func CurrentTime() int {
return audio.CurrentBytes()
// IsPlaying returns a boolean value which indicates if the channel buffer has data to play.
func IsPlaying(channel int) bool {
return audio.IsPlaying(channel)
}

View File

@ -17,8 +17,8 @@ package audio
const bufferSize = 1024
const SampleRate = 44100
var nextInsertion = 0
var currentBytes = 0
var nextInsertionPosition = 0
var currentPosition = 0
type channel struct {
l []float32
@ -55,8 +55,8 @@ func Play(channel int, l []float32, r []float32) bool {
if ch == nil {
return false
}
ch.l = append(ch.l, make([]float32, nextInsertion-len(ch.l))...)
ch.r = append(ch.r, make([]float32, nextInsertion-len(ch.r))...)
ch.l = append(ch.l, make([]float32, nextInsertionPosition-len(ch.l))...)
ch.r = append(ch.r, make([]float32, nextInsertionPosition-len(ch.r))...)
ch.l = append(ch.l, l...)
ch.r = append(ch.r, r...)
return true
@ -72,26 +72,21 @@ func Queue(channel int, l []float32, r []float32) {
ch.r = append(ch.r, r...)
}
func CurrentBytes() int {
return currentBytes + nextInsertion
}
func Update() {
nextInsertion += SampleRate / 60
nextInsertionPosition += SampleRate / 60
}
func channelAt(i int) *channel {
if i == -1 {
for _, ch := range channels {
if len(ch.l) <= nextInsertion {
return ch
for i, _ := range channels {
if !IsPlaying(i) {
return channels[i]
}
}
return nil
}
ch := channels[i]
if len(ch.l) <= nextInsertion {
return ch
if !IsPlaying(i) {
return channels[i]
}
return nil
}
@ -122,3 +117,8 @@ func loadChannelBuffers() (l, r []float32) {
}
return inputL, inputR
}
func IsPlaying(channel int) bool {
ch := channels[channel]
return nextInsertionPosition < len(ch.l)
}

View File

@ -31,13 +31,13 @@ func initialize() {
node = context.Call("createScriptProcessor", bufferSize, 0, 2)
node.Call("addEventListener", "audioprocess", func(e js.Object) {
defer func() {
currentBytes += bufferSize
currentPosition += bufferSize
}()
l := e.Get("outputBuffer").Call("getChannelData", 0)
r := e.Get("outputBuffer").Call("getChannelData", 1)
inputL, inputR := loadChannelBuffers()
nextInsertion -= min(bufferSize, nextInsertion)
nextInsertionPosition -= min(bufferSize, nextInsertionPosition)
for i := 0; i < bufferSize; i++ {
// TODO: Use copyFromChannel?
if len(inputL) <= i {