diff --git a/backend/main.go b/backend/main.go index 745b678..d0d392e 100644 --- a/backend/main.go +++ b/backend/main.go @@ -1,14 +1,20 @@ package main import ( - "io" + "bytes" + "encoding/binary" "log" - "os" + "os/exec" "github.com/kkdai/youtube/v2" ) -const ItagM4AAudio = 140 +const ( + ItagM4AAudio = 140 + SizeOfInt16 = 2 +) + +// TODO: process as stream to avoid loading full buffer in memory func main() { var client youtube.Client @@ -26,18 +32,29 @@ func main() { log.Fatal(err) } - file, err := os.Create("out.m4a") - if err != nil { - log.Fatal(err) + // TODO: force 44.1khz + cmd := exec.Command("ffmpeg", "-i", "-", "-f", "s16le", "-acodec", "pcm_s16le", "-") + cmd.Stdin = stream + + var out bytes.Buffer + cmd.Stdout = &out + + var errOut bytes.Buffer + cmd.Stderr = &errOut + + if err = cmd.Run(); err != nil { + log.Fatalf("err = %v, stdErr = %s", err, errOut.String()) } - defer file.Close() + log.Printf("byteLen = %d", out.Len()) - _, err = io.Copy(file, stream) - - if err != nil { - log.Fatal(err) + // TODO: reflect.Slice to avoid copying? + data := make([]uint16, 0, out.Len()/SizeOfInt16) + for i := 0; i < out.Len(); i += SizeOfInt16 { + v := binary.LittleEndian.Uint16(out.Bytes()[i : i+SizeOfInt16]) + data = append(data, v) } - log.Println("done") + log.Printf("intLen = %d", len(data)) + log.Printf("ints = %+v", data[0:8192]) }