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
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])
}