Skip to content

Instantly share code, notes, and snippets.

@declank
Created June 10, 2015 22:19
Show Gist options
  • Save declank/7ed8926383bd971cd1b7 to your computer and use it in GitHub Desktop.
Save declank/7ed8926383bd971cd1b7 to your computer and use it in GitHub Desktop.
[Golang] Simple music player that uses ffmpeg and portaudio
package main
import (
"code.google.com/p/portaudio-go/portaudio"
"encoding/binary"
"log"
"io"
"os"
"os/exec"
)
func getAudioFileArg() (filename string) {
if len(os.Args) < 2 {
log.Fatal("Missing argument: input file name")
}
filename = os.Args[1]
return
}
func chk(err error) {
if err != nil {
log.Fatal(err)
}
}
func createFfmpegPipe(filename string) (output io.ReadCloser) {
cmd := exec.Command("ffmpeg", "-i", filename, "-f", "s16le", "-")
output, err := cmd.StdoutPipe()
chk(err)
err = cmd.Start()
chk(err)
return
}
func playAudioFile(filename string) {
output := createFfmpegPipe(filename)
portaudio.Initialize()
defer portaudio.Terminate()
audiobuf := make([]int16, 16384)
stream, err := portaudio.OpenDefaultStream(0, 2, 44100, len(audiobuf), &audiobuf)
chk(err)
defer stream.Close()
chk(stream.Start())
defer stream.Stop()
for err = binary.Read(output, binary.LittleEndian, &audiobuf); err == nil; err = binary.Read(output, binary.LittleEndian, &audiobuf) {
chk(stream.Write())
}
chk(err)
}
func main() {
filename := getAudioFileArg()
playAudioFile(filename)
}
@rilysh
Copy link

rilysh commented Jul 21, 2022

audiobuf := make([]int16, 16384)
Use int32 instead int16 as int16 will create a 16 byte integer array, so the size of each buffer will be little less, which will make the whole audio output likely slow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment