-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
127 lines (112 loc) · 2.58 KB
/
main.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package main
import (
"flag"
"fmt"
"io"
"os"
"strings"
"github.com/go-audio/aiff"
"github.com/go-audio/audio"
"github.com/go-audio/wav"
"github.com/mattetti/audio/decoder"
)
var (
flagInput = flag.String("input", "", "The file to convert")
flagFormat = flag.String("format", "wav", "The format to convert to (wav or aiff)")
flagOutput = flag.String("output", "out", "The output filename")
)
func main() {
flag.Parse()
if *flagInput == "" {
fmt.Println("Provide an input file using the -input flag")
os.Exit(1)
}
switch strings.ToLower(*flagFormat) {
case "aiff", "aif":
*flagFormat = "aiff"
case "wave", "wav":
*flagFormat = "wav"
default:
fmt.Println("Provide a valid -format flag")
os.Exit(1)
}
f, err := os.Open(*flagInput)
if err != nil {
panic(err)
}
defer f.Close()
var dec decoder.Decoder
type encoder interface {
Write(b *audio.IntBuffer) error
Close() error
}
var enc encoder
var buf *audio.IntBuffer
wd := wav.NewDecoder(f)
if wd.IsValidFile() {
dec = wd
} else {
f.Seek(0, 0)
aiffd := aiff.NewDecoder(f)
if !aiffd.IsValidFile() {
fmt.Println("input file isn't a valid wav or aiff file")
os.Exit(1)
}
dec = aiffd
}
if !dec.WasPCMAccessed() {
err := dec.FwdToPCM()
if err != nil {
panic(err)
}
}
format := dec.Format()
var of *os.File
outputFilename := fmt.Sprintf("%s.%s", *flagOutput, *flagFormat)
switch *flagFormat {
case "wav", ".wav", "wave":
of, err = os.Create(outputFilename)
if err != nil {
panic(err)
}
defer of.Close()
enc = wav.NewEncoder(of, format.SampleRate, int(dec.SampleBitDepth()), format.NumChannels, 1)
case "aif", ".aif", "aiff", ".aiff":
of, err = os.Create(outputFilename)
if err != nil {
panic(err)
}
defer of.Close()
enc = aiff.NewEncoder(of, format.SampleRate, int(dec.SampleBitDepth()), format.NumChannels)
default:
fmt.Printf("output format %s not supported\n", *flagFormat)
os.Exit(1)
}
buf = &audio.IntBuffer{Format: format, Data: make([]int, 100000)}
var n int
var doneReading bool
for err == nil {
n, err = dec.PCMBuffer(buf)
if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
fmt.Println("failed to read the input file -", err)
os.Exit(1)
}
if n != len(buf.Data) {
buf.Data = buf.Data[:n]
doneReading = true
}
if err = enc.Write(buf); err != nil {
fmt.Println("failed to write to the output file -", err)
os.Exit(1)
}
if doneReading {
break
}
}
if err = enc.Close(); err != nil {
fmt.Println("failed to close the encoder stream")
os.Exit(1)
}
of.Close()
fmt.Println(outputFilename, "written to disk")
}