Skip to content

Commit

Permalink
audio : handle different file formats and resample
Browse files Browse the repository at this point in the history
  • Loading branch information
AkselsLedins committed Jan 23, 2019
1 parent 2817f7e commit 74253c7
Showing 1 changed file with 28 additions and 10 deletions.
38 changes: 28 additions & 10 deletions howl/audio.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,36 +3,54 @@ package howl
import (
"io"
"log"
"time"

"github.com/faiface/beep"
"github.com/faiface/beep/mp3"
"github.com/faiface/beep/speaker"
"github.com/faiface/beep/vorbis"
)

// InitAudio inits the audio speaker
func InitAudio() {
// the sample rate is set to 12000 as format.SampleRate does
// not return an accurate value
err := speaker.Init(12000, 12000)
sr := beep.SampleRate(22050)
err := speaker.Init(sr, sr.N(time.Second/2))
if err != nil {
log.Fatal("audio: could not init speaker")
return
}
}

// PlayAudioStream will output a stream to device speakers
func PlayAudioStream(as io.ReadCloser) {
func PlayAudioStream(as io.ReadCloser, format string) {
// we decode the ogg stream
s, _, _ := vorbis.Decode(as)
var s beep.StreamSeekCloser
var f beep.Format

if format == "vorbis" {
s, f, _ = vorbis.Decode(as)
} else if format == "mp3" {
s, f, _ = mp3.Decode(as)
}

// channel, which will signal the end of the playback.
playing := make(chan struct{})

// play the stream on the speaker
speaker.Play(beep.Seq(s, beep.Callback(func() {
// call back when the stream ended
close(playing)
})))
if format == "mp3" {
// play the stream on the speaker
speaker.Play(beep.Seq(beep.Resample(9, f.SampleRate, beep.SampleRate(22050), s), beep.Callback(func() {
// call back when the stream ended
close(playing)
})))
}

if format == "vorbis" {
// play the stream on the speaker
speaker.Play(beep.Seq(beep.Resample(9, f.SampleRate, beep.SampleRate(44000), s), beep.Callback(func() {
// call back when the stream ended
close(playing)
})))
}

// wait for the end of the stream
<-playing
Expand Down

0 comments on commit 74253c7

Please sign in to comment.