/
audiofile.go
245 lines (206 loc) · 6.9 KB
/
audiofile.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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
// Package audio contains structs and functions to allow operating on audio data
package audio
import (
"bufio"
"encoding/binary"
"io"
"io/ioutil"
"os"
"github.com/auroraapi/aurora-go/errors"
"github.com/gordonklaus/portaudio"
)
const (
BufSize = 1 << 10
SilentThresh = 1 << 10
SampleRate = 16000
NumChannels = 1
)
// File represents an audio file. It wraps the raw WAV data and allows you
// to operate with it using high-level operations, such as padding, trimming,
// playback, writing to file, recording, etc.
type File struct {
AudioData *WAV
playing bool
shouldStop bool
}
// WriteToFile writes the audio data to a file.
func (f *File) WriteToFile(filename string) error {
return ioutil.WriteFile(filename, f.AudioData.Data(), 0644)
}
// Pad adds silence to both the beginning and end of the audio data. Silence
// is specified in seconds.
func (f *File) Pad(seconds float64) {
// calculate number of bytes needed to pad given amount of seconds
bytes := float64(f.AudioData.NumChannels*f.AudioData.BitsPerSample/8) * float64(f.AudioData.SampleRate) * seconds
padding := make([]byte, int(bytes))
// copy the WAV parameters, set initial data to the left padding
newWav := NewWAVFromParams(&WAVParams{
NumChannels: f.AudioData.NumChannels,
SampleRate: f.AudioData.SampleRate,
BitsPerSample: f.AudioData.BitsPerSample,
AudioData: padding,
})
// add the original data and ther right padding
newWav.AddAudioData(f.AudioData.AudioData())
newWav.AddAudioData(padding)
// set the audio data to the new wav
f.AudioData = newWav
}
// PadLeft adds silence to the beginning of the audio data.
func (f *File) PadLeft(seconds float64) {
// calculate number of bytes needed to pad given amount of seconds
bytes := float64(f.AudioData.NumChannels*f.AudioData.BitsPerSample/8) * float64(f.AudioData.SampleRate) * seconds
padding := make([]byte, int(bytes))
// copy the WAV parameters, set initial data to the left padding
newWav := NewWAVFromParams(&WAVParams{
NumChannels: f.AudioData.NumChannels,
SampleRate: f.AudioData.SampleRate,
BitsPerSample: f.AudioData.BitsPerSample,
AudioData: padding,
})
// add the original data
newWav.AddAudioData(f.AudioData.AudioData())
// set the audio data to the new wav
f.AudioData = newWav
}
// PadRight adds silence to the end of the audio data.
func (f *File) PadRight(seconds float64) {
// calculate number of bytes needed to pad given amount of seconds
bytes := float64(f.AudioData.NumChannels*f.AudioData.BitsPerSample/8) * float64(f.AudioData.SampleRate) * seconds
padding := make([]byte, int(bytes))
// add the padding to the right
f.AudioData.AddAudioData(padding)
}
// TrimSilence trims silence from both ends of the audio data.
func (f *File) TrimSilence() {
// TODO: calibrate constants
f.AudioData.TrimSilent(0.03, 0.25)
}
// Stop the audio playback immediately.
func (f *File) Stop() {
if f.playing {
f.shouldStop = true
}
}
// Play the audio file to the default output
func (f *File) Play() error {
// initialize the underlying APIs for audio transmission
portaudio.Initialize()
defer portaudio.Terminate()
// create a buffer for audio to be put into
// hardcode 16-bit sample until i figure out a better way to do this
bufLen := int(BufSize * f.AudioData.NumChannels)
buf := make([]int16, bufLen)
// create the audio stream to write to
stream, err := portaudio.OpenDefaultStream(0, int(f.AudioData.NumChannels), float64(f.AudioData.SampleRate), BufSize, buf)
if err != nil {
return errors.NewFromErrorCodeInfo(errors.AudioFileOutputStreamNotOpened, err.Error())
}
defer stream.Close()
defer stream.Stop()
stream.Start()
// get audio data (without WAV header)
data := f.AudioData.AudioData()
step := bufLen * 2 // *2 since we need twice as many bytes to fill up `bufLen` in16s
f.playing = true
defer func() { f.playing = false }()
for i := 0; i < len(data); i += step {
// check if we should stop (user called f.Stop())
if f.shouldStop {
f.shouldStop = false
break
}
// need to convert each 2-bytes in [i, i+step] to 1 little endian int16
for j := 0; j < bufLen; j++ {
k := j * 2
buf[j] = int16(binary.LittleEndian.Uint16(data[i+k : i+k+2]))
}
// write the converted data into the stream
err := stream.Write()
if err != nil {
return errors.NewFromErrorCodeInfo(errors.AudioFileNotWritableStream, err.Error())
}
}
return nil
}
// NewRecordingStream records audio data according to the given parameters (just
// like `NewFileFromRecording`), however instead of creating an *audio.File, it
// streams the data to a Reader, which can be read as soon as data is available.
// It emits a WAV header before the actual data, but the length of the data is
// not correct. Therefore, the resulting WAV should be read until EOF.
func NewRecordingStream(length float64, silenceLen float64) io.Reader {
pr, pw := io.Pipe()
// Create a large buffer so that we don't block recording if the
// consumption of this data is too slow.
bufwr := bufio.NewWriterSize(pw, 1000*BufSize)
bufrd := bufio.NewReaderSize(pr, 1000*BufSize)
go func() {
defer pw.Close()
defer bufwr.Flush()
header := NewWAV().Data()
bufwr.Write(header)
ch := record(length, silenceLen)
for d := range ch {
if d.Error != nil {
return
}
bufwr.Write(d.Data)
}
}()
return bufrd
}
// NewFileFromRecording creates a new audio.File by recording from the default
// input stream. `length` specifies the maximum length of the recording in
// seconds. `silenceLen` specifies in seconds how much consecutive silence to
// wait for before ending the recording.
func NewFileFromRecording(length float64, silenceLen float64) (*File, error) {
ch := record(length, silenceLen)
audioData := make([]byte, 0)
for d := range ch {
if d.Error != nil {
return nil, d.Error
}
audioData = append(audioData, d.Data...)
}
return &File{
AudioData: NewWAVFromParams(&WAVParams{
NumChannels: NumChannels,
SampleRate: SampleRate,
BitsPerSample: 16,
AudioData: audioData,
}),
}, nil
}
// NewFileFromBytes creates a new audio.File from WAV data
func NewFileFromBytes(b []byte) (*File, error) {
wav, err := NewWAVFromData(b)
if err != nil {
return nil, err
}
return &File{wav, false, false}, err
}
// NewFileFromReader creates a new audio.File from an io.Reader
func NewFileFromReader(r io.Reader) (*File, error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
return NewFileFromBytes(data)
}
// NewFileFromFile creates a new audio.File from an os.File
func NewFileFromFile(f *os.File) (*File, error) {
return NewFileFromReader(f)
}
// NewFileFromFileName creates a new audio.File from the given filename
func NewFileFromFileName(f string) (*File, error) {
data, err := ioutil.ReadFile(f)
if err != nil {
return nil, err
}
return NewFileFromBytes(data)
}
// WAVData returns the wav data (header + audio data) contained in the
// audio file
func (f *File) WAVData() []byte {
return f.AudioData.Data()
}