poc: decode m4a to PCM with ffmpeg

This commit is contained in:
Rob Watson 2021-09-05 07:24:51 +02:00
parent d58ad5def1
commit b1ce4bc2b0
1 changed files with 29 additions and 12 deletions

View File

@ -1,14 +1,20 @@
package main package main
import ( import (
"io" "bytes"
"encoding/binary"
"log" "log"
"os" "os/exec"
"github.com/kkdai/youtube/v2" "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() { func main() {
var client youtube.Client var client youtube.Client
@ -26,18 +32,29 @@ func main() {
log.Fatal(err) log.Fatal(err)
} }
file, err := os.Create("out.m4a") // TODO: force 44.1khz
if err != nil { cmd := exec.Command("ffmpeg", "-i", "-", "-f", "s16le", "-acodec", "pcm_s16le", "-")
log.Fatal(err) 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) // TODO: reflect.Slice to avoid copying?
data := make([]uint16, 0, out.Len()/SizeOfInt16)
if err != nil { for i := 0; i < out.Len(); i += SizeOfInt16 {
log.Fatal(err) 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])
} }