audio: Introduce audio.Player

This commit is contained in:
Hajime Hoshi 2016-02-11 02:18:39 +09:00
parent d52118639d
commit 10650d1c6e
6 changed files with 25 additions and 15 deletions

View File

@ -122,7 +122,8 @@ func addNote() {
square(l, vol, freq, 0.25)
square(r, vol, freq, 0.25)
b := toBytes(l, r)
audio.Queue(&stream{bytes.NewReader(b)}, sampleRate)
p := audio.NewPlayer(&stream{bytes.NewReader(b)}, sampleRate)
p.Play()
}
func update(screen *ebiten.Image) error {

View File

@ -81,7 +81,8 @@ func (s *stream) Close() error {
func addNote(freq float64, vol float64) {
f := int(freq)
if n, ok := noteCache[f]; ok {
audio.Queue(&stream{bytes.NewReader(n)}, sampleRate)
p := audio.NewPlayer(&stream{bytes.NewReader(n)}, sampleRate)
p.Play()
return
}
length := len(pcm) * baseFreq / f
@ -98,7 +99,8 @@ func addNote(freq float64, vol float64) {
}
n := toBytes(l, r)
noteCache[f] = n
audio.Queue(&stream{bytes.NewReader(n)}, sampleRate)
p := audio.NewPlayer(&stream{bytes.NewReader(n)}, sampleRate)
p.Play()
}
var keys = []ebiten.Key{

View File

@ -25,7 +25,12 @@ type ReadSeekCloser interface {
io.Closer
}
// Queue queues the given data to the given channel.
type Player struct {
src ReadSeekCloser
sampleRate int
}
// NewPlayer creates a new player with the given data to the given channel.
// The given data is queued to the end of the buffer.
// This may not be played immediately when data already exists in the buffer.
//
@ -33,6 +38,13 @@ type ReadSeekCloser interface {
// without a header (e.g. RIFF header).
//
// TODO: Pass sample rate and num of channels.
func Queue(src ReadSeekCloser, sampleRate int) error {
return audio.Queue(src, sampleRate)
func NewPlayer(src ReadSeekCloser, sampleRate int) *Player {
return &Player{
src: src,
sampleRate: sampleRate,
}
}
func (p *Player) Play() error {
return audio.Play(p.src, p.sampleRate)
}

View File

@ -25,15 +25,10 @@ type ReadSeekCloser interface {
io.Closer
}
type chunk struct {
buffer ReadSeekCloser
sampleRate int
}
func Init() {
initialize()
}
func Queue(src ReadSeekCloser, sampleRate int) error {
return playChunk(src, sampleRate)
func Play(src ReadSeekCloser, sampleRate int) error {
return play(src, sampleRate)
}

View File

@ -68,7 +68,7 @@ func (a *audioProcessor) play() error {
return nil
}
func playChunk(src ReadSeekCloser, sampleRate int) error {
func play(src ReadSeekCloser, sampleRate int) error {
a := &audioProcessor{
src: src,
sampleRate: sampleRate,

View File

@ -24,7 +24,7 @@ import (
var players = map[*audio.Player]struct{}{}
func playChunk(src ReadSeekCloser, sampleRate int) error {
func play(src ReadSeekCloser, sampleRate int) error {
// TODO: audio.NewPlayer interprets WAV header, which we don't want.
// Use OpenAL or native API instead.
p, err := audio.NewPlayer(src, audio.Stereo16, int64(sampleRate))