Created
May 6, 2019 23:56
-
-
Save brydavis/4a4a5b4fb1b20356a545f5ae61ee7e4c to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ( | |
"bytes" | |
"encoding/binary" | |
"fmt" | |
"net/http" | |
"os" | |
"os/signal" | |
"github.com/bobertlo/go-mpg123/mpg123" | |
"github.com/gordonklaus/portaudio" | |
) | |
const sampleRate = 44100 | |
const seconds = 2 | |
func main() { | |
if len(os.Args) < 2 { | |
fmt.Println("missing required argument: input file name") | |
return | |
} | |
fmt.Println("Playing. Press Ctrl-C to stop.") | |
sig := make(chan os.Signal, 1) | |
signal.Notify(sig, os.Interrupt, os.Kill) | |
// create mpg123 decoder instance | |
decoder, err := mpg123.NewDecoder("") | |
chk(err) | |
fileName := os.Args[1] | |
chk(decoder.Open(fileName)) | |
defer decoder.Close() | |
// get audio format information | |
rate, channels, _ := decoder.GetFormat() | |
// make sure output format does not change | |
decoder.FormatNone() | |
decoder.Format(rate, channels, mpg123.ENC_SIGNED_16) | |
portaudio.Initialize() | |
defer portaudio.Terminate() | |
buffer := make([]float32, rate*seconds) | |
stream, err := portaudio.OpenDefaultStream( | |
1, 0, float64(rate), len(buffer), func(in []float32) { | |
for i := range buffer { | |
buffer[i] = in[i] | |
} | |
}) | |
chk(err) | |
chk(stream.Start()) | |
defer stream.Close() | |
go func() { | |
for { | |
audio := make([]byte, 2*len(buffer)) | |
_, err = decoder.Read(audio) | |
if err == mpg123.EOF { | |
break | |
} | |
chk(err) | |
chk(binary.Read(bytes.NewBuffer(audio), binary.LittleEndian, buffer)) | |
chk(stream.Write()) | |
select { | |
case <-sig: | |
return | |
default: | |
} | |
} | |
}() | |
http.HandleFunc("/audio", handleAudioStream) | |
http.ListenAndServe(":8080", nil) | |
} | |
func handleAudioStream(w http.ResponseWriter, r *http.Request) { | |
flusher, ok := w.(http.Flusher) | |
if !ok { | |
panic("expected http.ResponseWriter to be an http.Flusher") | |
} | |
w.Header().Set("Connection", "Keep-Alive") | |
w.Header().Set("Access-Control-Allow-Origin", "*") | |
w.Header().Set("X-Content-Type-Options", "nosniff") | |
w.Header().Set("Transfer-Encoding", "chunked") | |
w.Header().Set("Content-Type", "audio/wave") | |
for true { | |
binary.Write(w, binary.BigEndian, &buffer) | |
flusher.Flush() // Trigger "chunked" encoding and send a chunk... | |
return | |
} | |
} | |
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