examples/audio: Reuse SE audio.Player object

This commit is contained in:
Hajime Hoshi 2016-03-30 00:00:18 +09:00
parent 07968abfd6
commit 50b7ec59d4

View File

@ -18,7 +18,6 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"image/color" "image/color"
"io/ioutil"
"log" "log"
"time" "time"
@ -63,7 +62,7 @@ var (
audioContext *audio.Context audioContext *audio.Context
musicPlayer *Player musicPlayer *Player
seStream *wav.Stream seStream *wav.Stream
seBuffer []byte sePlayer *audio.Player
musicCh = make(chan *Player) musicCh = make(chan *Player)
seCh = make(chan *wav.Stream) seCh = make(chan *wav.Stream)
mouseButtonState = map[ebiten.MouseButton]int{} mouseButtonState = map[ebiten.MouseButton]int{}
@ -98,17 +97,17 @@ func (p *Player) updateSE() error {
if keyState[ebiten.KeyP] != 1 { if keyState[ebiten.KeyP] != 1 {
return nil return nil
} }
// Clone the buffer so that we can play the same SE mutiple times. if sePlayer == nil {
// TODO(hajimehoshi): This consumes memory. Can we avoid this? var err error
if seBuffer == nil { sePlayer, err = audioContext.NewPlayer(seStream)
b, err := ioutil.ReadAll(seStream)
if err != nil { if err != nil {
return err return err
} }
seBuffer = b
} }
sePlayer, err := audioContext.NewPlayer(&SEStream{bytes.NewReader(seBuffer)}) if sePlayer.IsPlaying() {
if err != nil { return nil
}
if err := sePlayer.Rewind(); err != nil {
return err return err
} }
return sePlayer.Play() return sePlayer.Play()