mirror of
https://github.com/cgzirim/seek-tune.git
synced 2025-12-20 18:34:20 +00:00
ConvertToWAV: Use temporary file to avoid FFmpeg overwrite errors
This commit is contained in:
parent
d16c6f1553
commit
de40d13c6f
1 changed files with 17 additions and 6 deletions
|
|
@ -8,8 +8,9 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
func ConvertToWAV(inputFilePath string, channels int) (wavFilePath string, errr error) {
|
// ConvertToWAV converts an input audio file to WAV format with specified channels.
|
||||||
_, err := os.Stat(inputFilePath)
|
func ConvertToWAV(inputFilePath string, channels int) (wavFilePath string, err error) {
|
||||||
|
_, err = os.Stat(inputFilePath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("input file does not exist: %v", err)
|
return "", fmt.Errorf("input file does not exist: %v", err)
|
||||||
}
|
}
|
||||||
|
|
@ -21,15 +22,19 @@ func ConvertToWAV(inputFilePath string, channels int) (wavFilePath string, errr
|
||||||
fileExt := filepath.Ext(inputFilePath)
|
fileExt := filepath.Ext(inputFilePath)
|
||||||
outputFile := strings.TrimSuffix(inputFilePath, fileExt) + ".wav"
|
outputFile := strings.TrimSuffix(inputFilePath, fileExt) + ".wav"
|
||||||
|
|
||||||
// Execute FFmpeg command to convert to WAV format with one channel (mono)
|
// Output file may already exists. If it does FFmpeg will fail as
|
||||||
|
// it cannot edit existing files in-place. Use a temporary file.
|
||||||
|
tmpFile := filepath.Join(filepath.Dir(outputFile), "tmp_"+filepath.Base(outputFile))
|
||||||
|
defer os.Remove(tmpFile)
|
||||||
|
|
||||||
cmd := exec.Command(
|
cmd := exec.Command(
|
||||||
"ffmpeg",
|
"ffmpeg",
|
||||||
"-y", // Automatically overwrite if file exists
|
"-y",
|
||||||
"-i", inputFilePath,
|
"-i", inputFilePath,
|
||||||
"-c", "pcm_s16le", // Output PCM signed 16-bit little-endian audio
|
"-c", "pcm_s16le",
|
||||||
"-ar", "44100",
|
"-ar", "44100",
|
||||||
"-ac", fmt.Sprint(channels),
|
"-ac", fmt.Sprint(channels),
|
||||||
outputFile,
|
tmpFile,
|
||||||
)
|
)
|
||||||
|
|
||||||
output, err := cmd.CombinedOutput()
|
output, err := cmd.CombinedOutput()
|
||||||
|
|
@ -37,6 +42,12 @@ func ConvertToWAV(inputFilePath string, channels int) (wavFilePath string, errr
|
||||||
return "", fmt.Errorf("failed to convert to WAV: %v, output %v", err, string(output))
|
return "", fmt.Errorf("failed to convert to WAV: %v, output %v", err, string(output))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Rename the temporary file to the output file
|
||||||
|
err = os.Rename(tmpFile, outputFile)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("failed to rename temporary file to output file: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
return outputFile, nil
|
return outputFile, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue