-
Notifications
You must be signed in to change notification settings - Fork 10
/
wav.go
84 lines (65 loc) · 1.69 KB
/
wav.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
package waveform
import "errors"
// Wav struct
type Wav struct {
WaveFormat WaveFormat
NumChannels uint16
SampleRate uint32
BitsPerSample uint16
DataChuckSize uint32
Data []byte
}
// GetData get wav audio data
func (w *Wav) GetData() (interface{}, error) {
bytePerSample := int(w.BitsPerSample / 8)
sampleParser, err := GetSampleParser(w.BitsPerSample, w.WaveFormat)
if err != nil {
return nil, err
}
if w.NumChannels == 1 {
sample := parseMonoSample(w.Data, bytePerSample, sampleParser)
bound, err := GetBound(w.BitsPerSample, w.WaveFormat)
if err != nil {
return nil, err
}
sample.Bound = bound
return sample, nil
}
if w.NumChannels == 2 {
sample := parseStereoSample(w.Data, bytePerSample, sampleParser)
bound, err := GetBound(w.BitsPerSample, w.WaveFormat)
if err != nil {
return nil, err
}
sample.Bound = bound
return sample, nil
}
return nil, errors.New("failed to sampled data from wav file")
}
func parseMonoSample(data []byte, bytePerSample int, parser Parser) *MonoData {
end := len(data) / bytePerSample
sample := make([]float64, 0)
for i := 0; i < end; i += bytePerSample {
s := parser(data[i : i+bytePerSample])
sample = append(sample, s)
}
return &MonoData{
Sample: sample,
}
}
func parseStereoSample(data []byte, bytePerSample int, parser Parser) *StereoData {
offset := bytePerSample * 2
end := len(data)
lSample := make([]float64, 0)
rSample := make([]float64, 0)
for i := 0; i < end; i += offset {
l := parser(data[i : i+bytePerSample])
r := parser(data[i+bytePerSample : i+offset])
lSample = append(lSample, l)
rSample = append(rSample, r)
}
return &StereoData{
LSample: lSample,
RSample: rSample,
}
}