-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaudio.py
264 lines (200 loc) · 6.07 KB
/
audio.py
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import pyaudio,wave,time
import mad
import os
from threading import Thread
import numpy as np
class AudioFile:
@classmethod
def load_file(cls, filename):
basename = os.path.basename(filename)
_,ext = os.path.splitext(basename)
if ext == '.mp3':
return MP3File(filename)
elif ext == '.wav':
return WaveFile(filename)
else:
return None
def __init__(self, filename):
pass
def get_nchannels(self):
pass
def get_samplerate(self):
pass
def get_samplewidth(self):
pass
def readframes(self):
pass
def close(self):
pass
def rewind(self):
pass
class WaveFile(AudioFile):
def __init__(self, filename):
self.wf = wave.open(filename, 'rb')
def get_nchannels(self):
return self.wf.getnchannels()
def get_samplerate(self):
return self.wf.getframerate()
def get_samplewidth(self):
return self.wf.getsampwidth()
def readframes(self, n):
return self.wf.readframes(n)
def close(self):
self.wf.close()
def rewind(self):
self.wf.rewind()
class MP3File(AudioFile):
def __init__(self, filename):
self.mf = mad.MadFile(filename)
self.buffer = bytearray()
def get_nchannels(self):
return 2
def get_samplerate(self):
return self.mf.samplerate()
def get_samplewidth(self):
return 2
def readframes(self,n):
rsz = 4*n
while len(self.buffer) < rsz:
# buffer is missing data to satisfy read size
block = self.mf.read()
if block is not None:
self.buffer += block
else:
break
block = self.buffer[:rsz]
self.buffer = self.buffer[rsz:]
return block
def close(self):
pass
def rewind(self):
self.mf.seek_time(0)
self.buffer = bytearray()
class MixerPlayer:
def __init__(self, mixer, p):
self.p = p
self.mixer = mixer
self.stream = None
self.af = None
self.filename = None
self.muted = False
self.loop = False
self.gain = 1.0
self.output_device_index = None
self.stop_callback = None
def register_stop_callback(self, f):
self.stop_callback = f
def register_status_callback(self, f):
self.status_callback = f
def load_wav(self, filename):
self.filename = filename
self.reset()
def reset(self):
# check if stream is running
if self.stream is not None and self.stream.is_active():
self.stream.stop_stream()
self.stream.close()
self.af.close()
if self.filename is None:
return
# load wave file
self.af = AudioFile.load_file(self.filename)
n = self.af.get_nchannels()
rate = self.af.get_samplerate()
sw = self.af.get_samplewidth()
# prepare stream
def callback(in_data, frame_count, time_info, status):
data = self.af.readframes(frame_count)
samples = np.frombuffer(data, dtype=np.int16)
if self.gain != 1.0:
samples = self.gain*samples
# update stream status
if self.status_callback is not None:
lvl = np.max(np.abs(samples))
fv = lvl/(1.0*np.iinfo(np.int16).max)
self.status_callback(fv)
# check if last packet was fetched
rv = pyaudio.paContinue
if len(data) < sw*n*frame_count:
# last frame
if self.loop:
# reload sample, load missing frames from beginning
self.af.rewind()
data = self.af.readframes(frame_count - len(data)/(sw*n))
samples = np.concatenate((samples, np.frombuffer(data, dtype=np.int16)))
else:
# stop stream
rv = pyaudio.paComplete
if self.stop_callback is not None:
self.stop_callback()
# mute sample
if self.muted:
samples = 0*samples
data = np.getbuffer(samples.astype(dtype=np.int16))
return (data, rv)
# create stream, do not start it
print "stream",sw,n,rate,self.output_device_index
self.stream = self.p.open(format=self.p.get_format_from_width(sw),
channels=n,
rate=rate,
output=True,
stream_callback=callback,
start=False,
output_device_index=self.output_device_index,
frames_per_buffer=1024*4)
def play(self):
if self.stream is None:
return
self.stream.start_stream()
def stop(self):
if self.stream is None:
return
self.stream.stop_stream()
def mute(self, b):
self.muted = b
def set_loop(self, b):
self.loop = b
def set_gain(self, gain):
self.gain = gain
def set_output_device(self, device):
self.output_device_index = self.mixer.get_device_index_by_name(device)
self.reset()
def shutdown(self):
if self.stream is not None:
self.stream.stop_stream()
self.stream.close()
if self.af is not None:
self.af.close()
class SoundBoardMixer:
def __init__(self):
self.p = pyaudio.PyAudio()
self.players = []
self.api_index = self.p.get_default_host_api_info()['index']
self.output_device = self.p.get_default_output_device_info()['name']
def get_device_index_by_name(self, device):
for i in xrange(0,self.p.get_device_count()):
obj = self.p.get_device_info_by_index(i)
if obj['name'] == device:
return obj['index']
def get_devices_using_api(self):
devices = []
for i in xrange(0,self.p.get_device_count()):
obj = self.p.get_device_info_by_index(i)
if obj['hostApi'] == self.api_index and obj['maxOutputChannels'] >= 2:
devices.append(obj['name'])
return devices
def new_player(self):
player = MixerPlayer(self, self.p)
player.set_output_device(self.output_device)
self.players.append(player)
return player
def remove_player(self, player):
self.players.remove(player)
def set_output_device(self, device):
if device is None:
device = self.p.get_default_output_device_info()['name']
self.output_device = device
for player in self.players:
player.set_output_device(device)
def get_output_device(self):
return self.output_device