audio: speaker: use Mixer to play sounds simultaneously

This commit is contained in:
faiface 2017-07-07 18:46:40 +02:00
parent 33c6f0ca5d
commit 006e4f5481
1 changed files with 14 additions and 26 deletions

View File

@ -12,7 +12,7 @@ import (
var ( var (
mu sync.Mutex mu sync.Mutex
streamer audio.Streamer mixer audio.Mixer
samples [][2]float64 samples [][2]float64
buf []byte buf []byte
player *oto.Player player *oto.Player
@ -64,29 +64,21 @@ func Unlock() {
mu.Unlock() mu.Unlock()
} }
// Play starts playing the provided Streamer through the speaker. // Play starts playing all provided Streamers through the speaker.
func Play(s audio.Streamer) { func Play(s ...audio.Streamer) {
mu.Lock() mu.Lock()
streamer = s mixer.Play(s...)
mu.Unlock() mu.Unlock()
} }
// update pulls new data from the playing Streamers and sends it to the speaker. Blocks until the // update pulls new data from the playing Streamers and sends it to the speaker. Blocks until the
// data is sent and started playing. // data is sent and started playing.
func update() { func update() {
// pull data from the streamer, if any
n := 0
if streamer != nil {
var ok bool
mu.Lock() mu.Lock()
n, ok = streamer.Stream(samples) mixer.Stream(samples)
mu.Unlock() mu.Unlock()
if !ok {
streamer = nil for i := range samples {
}
}
// convert samples to bytes
for i := range samples[:n] {
for c := range samples[i] { for c := range samples[i] {
val := samples[i][c] val := samples[i][c]
if val < -1 { if val < -1 {
@ -102,10 +94,6 @@ func update() {
buf[i*4+c*2+1] = high buf[i*4+c*2+1] = high
} }
} }
// fill the rest with silence
for i := n * 4; i < len(buf); i++ {
buf[i] = 0
}
// send data to speaker
player.Write(buf) player.Write(buf)
} }