audio: Inifite stream in JS

This commit is contained in:
Hajime Hoshi 2016-02-13 22:36:08 +09:00
parent 797bd04b1f
commit 5dbdb23b46

View File

@ -18,7 +18,7 @@ package audio
import ( import (
"io" "io"
"io/ioutil" "time"
"github.com/gopherjs/gopherjs/js" "github.com/gopherjs/gopherjs/js"
) )
@ -75,41 +75,55 @@ func toLR(data []byte) ([]int16, []int16) {
return l, r return l, r
} }
func (p *player) play() error { func (p *player) proceed() error {
// TODO: Reading all data at once is temporary implemntation. Treat this as stream. buf := make([]byte, 4096)
buf, err := ioutil.ReadAll(p.src) n, err := p.src.Read(buf)
if err != nil { if 0 < n {
return err const channelNum = 2
} const bytesPerSample = channelNum * 16 / 8
if len(buf) == 0 { b := context.Call("createBuffer", channelNum, n/bytesPerSample, p.sampleRate)
return nil l := b.Call("getChannelData", 0)
} r := b.Call("getChannelData", 1)
// TODO: p.position should be updated il, ir := toLR(buf[:n])
if p.bufferSource != nil { const max = 1 << 15
for i := 0; i < len(il); i++ {
l.SetIndex(i, float64(il[i])/max)
r.SetIndex(i, float64(ir[i])/max)
}
p.bufferSource = context.Call("createBufferSource")
p.bufferSource.Set("buffer", b)
p.bufferSource.Call("connect", context.Get("destination"))
p.bufferSource.Call("start", p.position) p.bufferSource.Call("start", p.position)
return nil p.position += b.Get("duration").Float()
} }
const channelNum = 2 return err
const bytesPerSample = channelNum * 16 / 8 }
b := context.Call("createBuffer", channelNum, len(buf)/bytesPerSample, p.sampleRate)
l := b.Call("getChannelData", 0) func (p *player) play() error {
r := b.Call("getChannelData", 1) // TODO: What if play is already called?
il, ir := toLR(buf) go func() {
const max = 1 << 15 defer p.close()
for i := 0; i < len(il); i++ { for {
l.SetIndex(i, float64(il[i])/max) err := p.proceed()
r.SetIndex(i, float64(ir[i])/max) if err == io.EOF {
} break
p.bufferSource = context.Call("createBufferSource") }
p.bufferSource.Set("buffer", b) if err != nil {
p.bufferSource.Call("connect", context.Get("destination")) // TODO: Record the last error
p.bufferSource.Call("start", p.position) panic(err)
p.position += b.Get("duration").Float() }
time.Sleep(1)
}
}()
return nil return nil
} }
func (p *player) close() error { func (p *player) close() error {
if p.bufferSource == nil {
return nil
}
p.bufferSource.Call("stop") p.bufferSource.Call("stop")
p.bufferSource.Call("disconnect") p.bufferSource.Call("disconnect")
p.bufferSource = nil
return nil return nil
} }