Last active
November 9, 2023 02:12
-
-
Save jannson/86e43136462c92eb1e91 to your computer and use it in GitHub Desktop.
ffmpeg convert audio
This file contains hidden or 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
func populateStdin(file []byte) func(io.WriteCloser) { | |
return func(stdin io.WriteCloser) { | |
defer stdin.Close() | |
io.Copy(stdin, bytes.NewReader(file)) | |
fmt.Println("copied ok") | |
} | |
} | |
func audio_m4a2mp3(data []byte) ([]byte, error) { | |
binary, lookErr := exec.LookPath("ffmpeg") | |
if lookErr != nil { | |
return nil, fmt.Errorf("not found ffmpeg: %v\n", lookErr) | |
} | |
//ffmpeg := exec.Command(binary, "-i", "pipe:0", "-map", "0:a", "-b:a", "24k", "-f", "mp3", "pipe:1") | |
ffmpeg := exec.Command(binary, "-i", "pipe:0", "-ab", "24k", "-f", "mp3", "pipe:1") | |
stdin, _ := ffmpeg.StdinPipe() | |
stdout, _ := ffmpeg.StdoutPipe() | |
//stderr, _ := ffmpeg.StderrPipe() | |
//echo := exec.Command("echo", os.Getenv("PATH")) | |
//tmpout, _ := echo.StdoutPipe() | |
//echo.Start() | |
//go io.Copy(os.Stdout, tmpout) | |
if err := ffmpeg.Start(); err != nil { | |
return nil, fmt.Errorf("exec error, %v\n", err) | |
} | |
fmt.Println("started") | |
go populateStdin(data)(stdin) | |
//go io.Copy(os.Stderr, stderr) | |
fmt.Println("input ok") | |
data2, err := ioutil.ReadAll(stdout) | |
if err != nil { | |
return nil, fmt.Errorf("readall error, %v\n", err) | |
} | |
//TODO for more tests | |
//http://stackoverflow.com/questions/11886531/terminating-a-process-started-with-os-exec-in-golang | |
done := make(chan error, 1) | |
go func() { | |
done <- ffmpeg.Wait() | |
}() | |
select { | |
case <-time.After(3 * time.Second): | |
if err := ffmpeg.Process.Kill(); err != nil { | |
log.Fatal("failed to kill: ", err) | |
} | |
<-done // allow goroutine to exit | |
return nil, fmt.Errorf("process killed") | |
case err := <-done: | |
if err != nil { | |
return nil, err | |
} | |
} | |
return data2, err | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment