Last active
November 13, 2024 16:30
-
-
Save aperture147/ad0f5b965912537d03b0e851bb95bd38 to your computer and use it in GitHub Desktop.
fix make buffer
This file contains 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" | |
"io/ioutil" | |
"log" | |
"os" | |
"os/exec" | |
) | |
func check(err error) { | |
if err != nil { | |
log.Fatalln(err) | |
} | |
} | |
func main() { | |
file, err := os.Open("test.mp3") // open file | |
check(err) | |
defer file.Close() | |
buf, err := ioutil.ReadAll(file) | |
check(err) | |
cmd := exec.Command("ffmpeg", "-y", // Yes to all | |
//"-hide_banner", "-loglevel", "panic", // Hide all logs | |
"-i", "pipe:0", // take stdin as input | |
"-map_metadata", "-1", // strip out all (mostly) metadata | |
"-c:a", "libmp3lame", // use mp3 lame codec | |
"-vsync", "2", // suppress "Frame rate very high for a muxer not efficiently supporting it" | |
"-b:a", "128k", // Down sample audio birate to 128k | |
"-f", "mp3", // using mp3 muxer (IMPORTANT, output data to pipe require manual muxer selecting) | |
"pipe:1", // output to stdout | |
) | |
// resultBuffer := bytes.NewBuffer(make([]byte, 0)) // uncomment this line if you don't want to preallocate the buffer | |
resultBuffer := bytes.NewBuffer(make([]byte, 5*1024*1024)) // pre allocate 5MiB buffer | |
cmd.Stderr = os.Stderr // bind log stream to stderr | |
cmd.Stdout = resultBuffer // stdout result will be written here | |
stdin, err := cmd.StdinPipe() // Open stdin pipe | |
check(err) | |
err = cmd.Start() // Start a process on another goroutine | |
check(err) | |
_, err = stdin.Write(buf) // pump audio data to stdin pipe | |
check(err) | |
err = stdin.Close() // close the stdin, or ffmpeg will wait forever | |
check(err) | |
err = cmd.Wait() // wait until ffmpeg finish | |
check(err) | |
outputFile, err := os.Create("out.mp3") // create new file | |
check(err) | |
defer outputFile.Close() | |
_, err = outputFile.Write(resultBuffer.Bytes()) // write result buffer to file | |
check(err) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sorry, I couldn't reproduce this problem. As the log result, your file input might not be a mp3 file:
Format mp3 detected only with low score of 1, misdetection possible!
This is my setup and my sample audio file, can you try my sample?
OS: Ubuntu 20.04.5 LTS x86_64
ffmpeg -version
:go version
:go version go1.18.5 linux/amd64
Sample MP3 file: Brain Damage - Pink Floyd