-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaudio_manager.jl
427 lines (369 loc) · 16.8 KB
/
audio_manager.jl
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
# Copyright (C) 2013-2014 Samuele Carcagno <[email protected]>
# This file is part of PsychoJulia
# PsychoJulia is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# PsychoJulia is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with PsychoJulia. If not, see <http://www.gnu.org/licenses/>.
#using AudioIO
function playSound(snd, fs, nbits, writewav, fname, prm)
wavmanager = prm["pref"]["sound"]["wavmanager"]
playCmd = prm["pref"]["sound"]["playCommand"]
if in(playCmd, ["AaudioIO"])#write wav before appending zeros in this case
if writewav == true
if wavmanager == "WAV"
wavwrite(ns, fname, Fs=fs, nbits=nbits)
end
end
end
if prm["pref"]["sound"]["appendSilence"] > 0
duration = prm["pref"]["sound"]["appendSilence"]/1000 #convert from ms to sec
nSamples = int(round(duration * fs))
silenceToAppend = zeros(nSamples, 2)
snd = vcat(snd, silenceToAppend)
end
#AudioIO
if in(playCmd, ["AudioIO"])
nSamples = size(snd)[1]
play(snd)
else
if wavmanager == "WAV"
wavwrite(snd, fname, Fs=fs, nbits=nbits)
end
run(`$playCmd $fname`)
end
return
end
## def decimalToBinary(x, n):
## """Convert an integer in decimal format to binary string representation
## x: decimal integer
## n: number of positions
## """
## res = bin(x)
## res = res[2:len(res)] #strip the 0b header
## padSize = n - len(res)
## res = '0'*padSize + res
## return res
## class audioManager():
## def __init__(self, parent):
## self.parent = parent
## self.prm = parent.prm
## if self.prm["pref"]["sound"]["wavmanager"] == "scipy":
## from scipy.io import wavfile
## self.wavfile = wavfile
## self.initializeAudio()
## def initializeAudio(self):
## self.playCmd = self.prm['pref']['sound']['playCommand']
## try: #if alsaaudio device was open close it
## self.device.close()
## except:
## pass
## try:#if paManager was open close it
## self.paManager.terminate() #actually closing the stream introduces offset clicks!
## except:
## pass
## if self.playCmd == "alsaaudio":
## try:
## self.device = alsaaudio.PCM(type=alsaaudio.PCM_PLAYBACK, mode=alsaaudio.PCM_NORMAL, card=self.prm["pref"]["sound"]["alsaaudioDevice"])
## except:
## self.device = alsaaudio.PCM(type=alsaaudio.PCM_PLAYBACK, mode=alsaaudio.PCM_NORMAL, card=self.listAlsaaudioPlaybackCards()[0])
## elif self.playCmd == "pyaudio":
## self.paManager = pyaudio.PyAudio()
## def playSound(self, snd, fs, nbits, writewav, fname):
## wavmanager = self.prm["pref"]["sound"]["wavmanager"]
## playCmd = str(self.playCmd)
## enc = "pcm"+ str(nbits)
## if writewav == True:
## fname = fname
## else:
## (hnl, fname) = mkstemp("tmp_snd.wav")
## if playCmd in ['alsaaudio', 'pyaudio']:#write wav before appending zeros in this case
## if writewav == True:
## if wavmanager == "scipy":
## self.scipy_wavwrite(fname, fs, nbits, snd)
## if self.prm["pref"]["sound"]["appendSilence"] > 0:
## duration = self.prm["pref"]["sound"]["appendSilence"]/1000 #convert from ms to sec
## nSamples = int(round(duration * fs))
## silenceToAppend = zeros((nSamples, 2))
## snd = concatenate((snd, silenceToAppend), axis=0)
## #alsaaudio
## if playCmd in ['alsaaudio', 'pyaudio']:
## nSamples = snd.shape[0]
## nChannels = snd.shape[1]
## bufferSize = self.prm["pref"]["sound"]["bufferSize"]
## if bufferSize < 1:
## bufferSize = nSamples
## nSeg = 1
## else:
## nSeg = int(ceil(nSamples/bufferSize))
## padSize = (nSeg*bufferSize) - nSamples
## pad = zeros((padSize, nChannels))
## snd = concatenate((snd, pad), axis=0)
## if playCmd == "alsaaudio":
## device = self.device
## device.setchannels(nChannels)
## device.setrate(fs)
## device.setperiodsize(bufferSize)
## if nbits == 16:
## data = snd*(2.**15)
## data = data.astype(int16)
## device.setformat(alsaaudio.PCM_FORMAT_S16_LE)
## elif nbits == 32:
## data = snd*(2.**31)
## data = data.astype(int32)
## device.setformat(alsaaudio.PCM_FORMAT_S32_LE)
## for i in range(nSeg):
## thisData = data[i*bufferSize:((i*bufferSize)+bufferSize)][:]
## device.write(thisData)
## elif playCmd == "pyaudio":
## if nbits == 16:
## data = snd*(2.**15)
## data = data.astype(int16)
## sampleFormat = pyaudio.paInt16
## elif nbits == 32:
## data = snd*(2.**31)
## data = data.astype(int32)
## sampleFormat = pyaudio.paInt32
## # try:
## # self.stream
## # except:
## stream = self.paManager.open(format=sampleFormat,
## channels = nChannels,
## rate = fs,
## output = True,
## input_device_index = self.prm["pref"]["sound"]["pyaudioDevice"],
## output_device_index=None,
## frames_per_buffer=bufferSize)
## for i in range(nSeg):
## thisData = data[i*bufferSize:((i*bufferSize)+bufferSize)][:]
## stream.write(thisData, num_frames=bufferSize)
## stream.stop_stream()
## stream.close()
## #time.sleep((bufferSize/fs)+0.02)
## #self.stream.close() #stream seems to close before sound finished playing
## else:
## if wavmanager == "scipy":
## self.scipy_wavwrite(fname, fs, nbits, snd)
## if platform.system() == "Windows":
## if playCmd == "winsound":
## winsound.PlaySound(fname, winsound.SND_FILENAME)
## else:
## subprocess.call(playCmd + " " + fname, shell=True)
## if writewav == False:
## os.close(hnl)
## os.remove(fname)
## else:
## subprocess.call(playCmd + " " + fname, shell=True)
## if writewav == False:
## os.close(hnl)
## os.remove(fname)
## return
## def playSoundWithTrigger(self, snd, fs, nbits, writewav, fname, triggerNumber):
## if writewav == True:
## fname = fname
## else:
## (hnl, fname) = mkstemp("tmp_snd.wav")
## (hnl1, snd_fname) = mkstemp("snd.wav")
## (hnl2, trigon_fname) = mkstemp("trig-on.wav")
## (hnl3, trigoff_fname) = mkstemp("trig-off.wav")
## self.scipy_wavwrite(snd_fname, fs, nbits, snd)
## playCmd = self.playCmd
## if playCmd == "winsound": #does not really play with trigger for the moment
## winsound.PlaySound(snd_fname, winsound.SND_FILENAME)
## else:
## nSamp = snd.shape[0]
## triggerDur = self.prm["pref"]["general"]["triggerDur"]
## nSamplesTrigger = ceil(triggerDur * fs)
## chOff = zeros((nSamp, 1))
## chOn = zeros((nSamp, 1))
## chOn[0:nSamplesTrigger,:] = 0.5
## self.scipy_wavwrite(trigoff_fname, fs, nbits, chOff)
## self.scipy_wavwrite(trigon_fname, fs, nbits, chOn)
## triggerCode = decimalToBinary(triggerNumber, 8)
## triggerCode = triggerCode[::-1] #reverse it
## soxCmd = "sox -M " + snd_fname
## for i in range(6):
## if triggerCode[i] == '1':
## wavToCat = " " + trigoff_fname
## else:
## wavToCat = " " + trigon_fname
## soxCmd = soxCmd + wavToCat
## soxCmd = soxCmd + " " + fname
## subprocess.call(soxCmd, shell=True)
## os.close(hnl1)
## os.close(hnl2)
## os.close(hnl3)
## os.remove(trigoff_fname)
## os.remove(trigon_fname)
## os.remove(snd_fname)
## subprocess.call(playCmd + " " + fname, stdout=self.prm['cmdOutFileHandle'], stderr=self.prm['cmdOutFileHandle'], shell=True)
## if writewav == False:
## os.close(hnl)
## os.remove(fname)
## def loadWavFile(self, fName, desiredLevel, maxLevel, channel):
## wavmanager = self.prm["pref"]["sound"]["wavmanager"]
## if wavmanager == "scipy":
## fs, snd = self.wavfile.read(fName)
## if snd.dtype == "int16":
## snd = snd / (2.**15)
## nbits = 16
## elif snd.dtype == "int32":
## snd = snd / (2.**31)
## nbits = 32
## rms1 = sqrt(mean(snd[:,0]*snd[:,0]))
## rms2 = sqrt(mean(snd[:,1]*snd[:,1]))
## if rms1 > 0:
## normSnd1 = snd[:,0] / (rms1 * sqrt(2))
## else:
## normSnd1 = snd[:,0]
## if rms2 > 0:
## normSnd2 = snd[:,1] / (rms2 * sqrt(2))
## else:
## normSnd2 = snd[:,1]
## desiredAmp = 10**((desiredLevel - maxLevel)/20)
## snd[:,0] = desiredAmp * normSnd1
## snd[:,1] = desiredAmp * normSnd2
## if channel == "Right":
## snd[:, 0] = zeros(len(snd[:,0]))
## elif channel == "Left":
## snd[:, 1] = zeros(len(snd[:,1]))
## elif channel == "Original":
## pass
## return snd, fs, nbits
## def read_wav(self, fName):
## wavmanager = self.prm["pref"]["sound"]["wavmanager"]
## if wavmanager == "scipy":
## fs, snd = self.wavfile.read(fName)
## if snd.dtype == "int16":
## snd = snd / (2.**15)
## elif snd.dtype == "int32":
## snd = snd / (2.**31)
## return snd, fs
## def scipy_wavwrite(self, fname, fs, nbits, data):
## if nbits == 16:
## data = data*(2.**15)
## data = data.astype(int16)
## elif nbits == 24:
## print("error, cannot save 24 bits at the moment")
## elif nbits == 32:
## data = data*(2.**31)
## data = data.astype(int32)
## if nbits != 24:
## self.wavfile.write(fname, fs, data)
## def listAlsaaudioPlaybackCards(self):
## playbackCardList = []
## for card in alsaaudio.cards():
## try:
## alsaaudio.PCM(type=alsaaudio.PCM_PLAYBACK, mode=alsaaudio.PCM_NORMAL, card=card)
## playbackCardList.append(card)
## except:
## pass
## return playbackCardList
## class threadedAudioPlayer(QThread):
## def __init__(self, parent):
## QThread.__init__(self, parent)
## self.prm = self.parent().prm
## self.audioManager = audioManager(self)
## self.exiting = False
## def playThreadedSound(self, snd, sampRate, nbits, playCmd, writewav, fName):
## self.snd = snd
## self.sampRate = sampRate
## self.nbits = nbits
## self.playCmd = playCmd
## wavmanager = self.prm["pref"]["sound"]["wavmanager"]
## if writewav == True: #write the sound before appending zeros
## if wavmanager == "scipy":
## self.audioManager.scipy_wavwrite(fName, sampRate, nbits, snd)
## if self.prm["pref"]["sound"]["appendSilence"] > 0:
## duration = self.prm["pref"]["sound"]["appendSilence"]/1000 #convert from ms to sec
## nSamples = int(round(duration * sampRate))
## silenceToAppend = zeros((nSamples, 2))
## self.snd = concatenate((self.snd, silenceToAppend), axis=0)
## #self.playCmd = str(self.playCmd)
## if self.playCmd in ['alsaaudio', 'pyaudio']:
## nSamples = self.snd.shape[0]
## nChannels = self.snd.shape[1]
## self.bufferSize = self.prm["pref"]["sound"]["bufferSize"]
## if self.bufferSize < 1:
## self.bufferSize = nSamples
## self.nSeg = 1
## else:
## self.nSeg = int(ceil(nSamples/self.bufferSize))
## padSize = (self.nSeg*self.bufferSize) - nSamples
## pad = zeros((padSize, nChannels))
## self.snd = concatenate((self.snd, pad), axis=0)
## if playCmd == "alsaaudio":
## self.device = alsaaudio.PCM(type=alsaaudio.PCM_PLAYBACK, mode=alsaaudio.PCM_NORMAL, card=self.prm["pref"]["sound"]["alsaaudioDevice"])
## self.device.setchannels(nChannels)
## self.device.setrate(sampRate)
## self.device.setperiodsize(self.bufferSize)
## if self.nbits == 16:
## self.data = self.snd*(2.**15)
## self.data = self.data.astype(int16)
## self.device.setformat(alsaaudio.PCM_FORMAT_S16_LE)
## elif self.nbits == 32:
## self.data = self.snd*(2.**31)
## self.data = self.data.astype(int32)
## self.device.setformat(alsaaudio.PCM_FORMAT_S32_LE)
## elif playCmd == "pyaudio":
## paManager = pyaudio.PyAudio()
## if self.nbits == 16:
## self.data = self.snd*(2.**15)
## self.data = self.data.astype(int16)
## sampleFormat = pyaudio.paInt16
## elif nbits == 32:
## self.data = self.snd*(2.**31)
## self.data = self.data.astype(int32)
## sampleFormat = pyaudio.paInt32
## self.stream = paManager.open(format =sampleFormat,
## channels = nChannels,
## rate = sampRate,
## output = True,
## input_device_index = self.prm["pref"]["sound"]["pyaudioDevice"],
## output_device_index=None,
## frames_per_buffer=self.bufferSize)
## #QThread.start(self)
## self.start()
## def run(self):
## i = 0
## while self.exiting == False and self.nSeg > 0:
## if self.playCmd == "alsaaudio":
## thisData = self.data[i*self.bufferSize:((i*self.bufferSize)+self.bufferSize)][:]
## self.device.write(thisData)
## elif self.playCmd == "pyaudio":
## thisData = self.data[i*self.bufferSize:((i*self.bufferSize)+self.bufferSize)][:]
## self.stream.write(thisData, num_frames=self.bufferSize)
## i = i+1
## self.nSeg = self.nSeg -1
## #stream.close()
## #paManager.terminate() #actually closing the stream introduces offset clicks!
## def __del__(self):
## #the thread will finish before being terminated
## self.exiting = True
## self.wait()
## self.terminate()
## class threadedExternalAudioPlayer(QThread):
## def __init__(self, parent):
## QThread.__init__(self, parent)
## self.prm = self.parent().prm
## self.audioManager = audioManager(self)
## self.exiting = False
## def playThreadedSound(self, sound, sampRate, bits, cmd, writewav, fName):
## self.sound = sound
## self.sampRate = sampRate
## self.bits = bits
## self.cmd = cmd
## self.writewav = writewav
## self.fName = fName
## self.start()
## def run(self):
## self.audioManager.playSound(self.sound, self.sampRate, self.bits, self.writewav, self.fName)
## def __del__(self):
## #the thread will finish before being terminated
## self.wait()
## self.terminate()