Created
June 10, 2015 22:19
-
-
Save declank/7ed8926383bd971cd1b7 to your computer and use it in GitHub Desktop.
[Golang] Simple music player that uses ffmpeg and portaudio
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
audiobuf := make([]int16, 16384)
Use
int32
insteadint16
asint16
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.