Skip to content

Commit

Permalink
Merge pull request #595 from EngoEngine/laggy-audio
Browse files Browse the repository at this point in the history
separate oto on its own goroutine
  • Loading branch information
Noofbiz authored Oct 30, 2018
2 parents 70b3dfc + 6a2fdc8 commit 8b755d9
Showing 1 changed file with 25 additions and 7 deletions.
32 changes: 25 additions & 7 deletions common/audio.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,9 @@ type audioEntity struct {
type AudioSystem struct {
entities []audioEntity

otoPlayer *oto.Player
bufsize int
otoPlayer *oto.Player
bufsize int
audioReadC, audioCloser chan struct{}
}

// New is called when the AudioSystem is added to the world.
Expand All @@ -48,11 +49,30 @@ func (a *AudioSystem) New(w *ecs.World) {
if err != nil {
log.Printf("audio error. Unable to create new OtoPlayer: %v \n\r", err)
}
a.audioCloser = make(chan struct{})
runtime.SetFinalizer(a.otoPlayer, func(p *oto.Player) {
if err := p.Close(); err != nil {
log.Printf("audio error. Unable to close OtoPlayer: %v \n\r", err)
}
close(a.audioCloser)
})
// run oto on a separate thread so it doesn't slow down updates
a.audioReadC = make(chan struct{}, 10)
go func() {
for {
select {
case <-a.audioReadC:
buf := make([]byte, a.bufsize)
a.read(buf)

if _, err := a.otoPlayer.Write(buf); err != nil {
log.Printf("error copying to OtoPlayer: %v \r\n", err)
}
case <-a.audioCloser:
return
}
}
}()
masterVolume = 1
}

Expand Down Expand Up @@ -85,11 +105,9 @@ func (a *AudioSystem) Remove(basic ecs.BasicEntity) {

// Update is called once per frame, and updates/plays the players in the AudioSystem
func (a *AudioSystem) Update(dt float32) {
buf := make([]byte, a.bufsize)
a.read(buf)

if _, err := a.otoPlayer.Write(buf); err != nil {
log.Printf("error copying to OtoPlayer: %v \r\n", err)
select {
case a.audioReadC <- struct{}{}:
default:
}
}

Expand Down

0 comments on commit 8b755d9

Please sign in to comment.