Skip to content

Instantly share code, notes, and snippets.

@ygabuev
Last active August 20, 2021 09:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ygabuev/a2d212286b4895e392074697755d91e6 to your computer and use it in GitHub Desktop.
Save ygabuev/a2d212286b4895e392074697755d91e6 to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"encoding/binary"
"io"
"os"
"os/signal"
"github.com/gordonklaus/portaudio"
"github.com/hajimehoshi/go-mp3"
)
func main() {
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, os.Kill)
fileName := "sample.mp3"
f, err := os.Open(fileName)
chk(err)
defer f.Close()
decoder, err := mp3.NewDecoder(f)
chk(err)
// get audio format information
rate := decoder.SampleRate()
channels := 2
portaudio.Initialize()
defer portaudio.Terminate()
bufsize := 8192
out := make([]int16, bufsize)
stream, err := portaudio.OpenDefaultStream(0, channels, float64(rate), len(out), &out)
chk(err)
defer stream.Close()
chk(stream.Start())
defer stream.Stop()
audio := make([]byte, 2*len(out))
for {
_, err = decoder.Read(audio)
if err == io.EOF {
break
}
chk(err)
chk(binary.Read(bytes.NewReader(audio), binary.LittleEndian, out))
chk(stream.Write())
select {
case <-sig:
return
default:
}
}
}
func chk(err error) {
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment