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.

Revisions

  1. declank created this gist Jun 10, 2015.
    61 changes: 61 additions & 0 deletions go-play-music.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,61 @@
    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)
    }