Skip to content

Instantly share code, notes, and snippets.

@fresonn
Last active October 5, 2022 18:29
Show Gist options
  • Save fresonn/b27bd867967554a07b3e2491db6d015f to your computer and use it in GitHub Desktop.
Save fresonn/b27bd867967554a07b3e2491db6d015f to your computer and use it in GitHub Desktop.
Process audio by ffmpeg in Golang
tempDirLoc := os.TempDir()
tempFile, err := os.CreateTemp(tempDirLoc, "audio-*.mp3")
if err != nil {
fmt.Println(err)
}
defer tempFile.Close()
fileBytes, err := io.ReadAll(input.Audiofile.File) // from multipart form
if err != nil {
fmt.Println(err)
}
tempFile.Write(fileBytes)
defer os.Remove(tempFile.Name())
fmt.Println("Open:", tempFile.Name())
// ffmpeg -y -i FILE -map 0:a -c:a copy -map_metadata -1 FILE
ffErr := ffmpeg.Input(tempFile.Name()).
Output(tempDirLoc+"/result.mp3", ffmpeg.KwArgs{"map": "0:a", "c:a": "copy", "map_metadata": -1}).
OverWriteOutput().ErrorToStdOut().Run()
if ffErr != nil {
fmt.Println(ffErr)
}
data, err := ffmpeg.Probe(tempDirLoc + "/result.mp3")
if err != nil {
panic(err)
}
log.Println("got audio info", data)
type AudioInfo struct {
Streams []struct {
CodecType string `json:"codec_type"`
CodecName string `json:"codec_name"`
} `json:"streams"`
Format struct {
Duration string `json:"duration"`
} `json:"format"`
}
ai := &AudioInfo{}
err = json.Unmarshal([]byte(data), ai)
if err != nil {
panic(err)
}
duration := ai.Format.Duration
codecType := ai.Streams[0].CodecType
codecName := ai.Streams[0].CodecName
fmt.Printf("Final info --> CodecType: %s, CodecName: %s, duration: %s\n", codecType, codecName, duration)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment