forked from cgzirim/seek-tune
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvert.go
78 lines (64 loc) · 1.83 KB
/
convert.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package wav
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)
// ConvertToWAV converts an input audio file to WAV format with specified channels.
func ConvertToWAV(inputFilePath string, channels int) (wavFilePath string, err error) {
_, err = os.Stat(inputFilePath)
if err != nil {
return "", fmt.Errorf("input file does not exist: %v", err)
}
if channels < 1 || channels > 2 {
channels = 1
}
fileExt := filepath.Ext(inputFilePath)
outputFile := strings.TrimSuffix(inputFilePath, fileExt) + ".wav"
// 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(
"ffmpeg",
"-y",
"-i", inputFilePath,
"-c", "pcm_s16le",
"-ar", "44100",
"-ac", fmt.Sprint(channels),
tmpFile,
)
output, err := cmd.CombinedOutput()
if err != nil {
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
}
func ReformatWAV(inputFilePath string, channels int) (reformatedFilePath string, errr error) {
if channels < 1 || channels > 2 {
channels = 1
}
fileExt := filepath.Ext(inputFilePath)
outputFile := strings.TrimSuffix(inputFilePath, fileExt) + "rfm.wav"
cmd := exec.Command(
"ffmpeg",
"-y",
"-i", inputFilePath,
"-c", "pcm_s16le",
"-ar", "44100",
"-ac", fmt.Sprint(channels),
outputFile,
)
output, err := cmd.CombinedOutput()
if err != nil {
return "", fmt.Errorf("failed to convert to WAV: %v, output %v", err, string(output))
}
return outputFile, nil
}