-
Notifications
You must be signed in to change notification settings - Fork 0
/
tap.py
executable file
·415 lines (318 loc) · 10.8 KB
/
tap.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
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
# IMPORTS:
import sys
import pyaudio
import time
import random
import os
import wave
import thread
from pyAudioAnalysis import audioTrainTest as aT
import threading
import time
from pydub import AudioSegment
import numpy
import Queue
from os import listdir
from os.path import isfile, join
from pynput import keyboard
from scipy import signal
import matplotlib.pyplot as plt
# Thread Control
lo = threading.Lock()
onlyfiles = []
# On press
def on_press(key):
global keyPressedFlag
global keyPressed
try:
k = key.char # single-char keys
except:
k = key.name # other keys
if key == keyboard.Key.esc:
keyPressedFlag = True # stop listener
return False
# if k in ['1', '2', 'left', 'right']: # keys interested
# self.keys.append(k) # store it in global-like variable
# print('Key pressed: ' + k)
# Thread Class to play Audio segment
class playThread(threading.Thread):
def __init__(self, file):
threading.Thread.__init__(self)
self.file = file
def run(self):
CHUNK = 1024
wf = wave.open(self.file, 'rb')
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
output=True)
data = wf.readframes(CHUNK)
while data != '':
stream.write(data)
data = wf.readframes(CHUNK)
stream.stop_stream()
stream.close()
p.terminate()
# Thread Class to queue record stream
class recordQThread(threading.Thread):
def __init__(self, frames=[]):
threading.Thread.__init__(self)
self.frames = frames
def run(self):
global q
RATE = 44100
audiofile = AudioSegment(data=b''.join(self.frames), sample_width=2, frame_rate=RATE, channels=2)
data = numpy.fromstring(audiofile._data, numpy.int16)
len(data)
x = []
for chn in xrange(audiofile.channels):
x.append(data[chn::audiofile.channels])
x = numpy.array(x).T
# print "X: " + str(len(x))
lo.acquire()
# print "Q: " + str(q.qsize())
q.put(x)
lo.release()
# Thread Class to record Audio Segment
class recordThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
global q
global keyPressedFlag
global keyPressed
keyPressedFlag = False
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
output=True,
frames_per_buffer=CHUNK)
# print("* HIT!")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
recordQThread(frames).start()
while True:
# print "Frames: " + str(len(frames))
frames.remove(frames[0])
data = stream.read(CHUNK)
frames.append(data)
recordQThread(frames).start()
'''audiofile = AudioSegment(data=b''.join(frames),sample_width=2,frame_rate=RATE,channels=2)
data = numpy.fromstring(audiofile._data, numpy.int16)
x = []
for chn in xrange(audiofile.channels):
x.append(data[chn::audiofile.channels])
x = numpy.array(x).T
lo.acquire()
q.put(x)
lo.release()'''
if keyPressedFlag:
break
# print "Exiting " + self.name
def ConvertToImage():
# Recording parameters
CHUNK = 2048
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 22050
RECORD_SECONDS = 0.5
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
output=True,
frames_per_buffer=CHUNK)
frames = []
for i in range(0, int(RATE * RECORD_SECONDS) / CHUNK):
data = stream.read(CHUNK)
frames.append(data)
audiofile = AudioSegment(data=b''.join(frames), sample_width=2, frame_rate=RATE, channels=2)
print "audiofile!!!"
print audiofile.get_array_of_samples()
# data = numpy.fromstring(audiofile._data, numpy.int16)
import pylab
data = pylab.fromstring(audiofile._data, 'int16')
print data
f, t, Sxx = signal.spectrogram(data, 22050)
plt.pcolormesh(t, f, Sxx)
plt.ylim(0, 8000)
plt.axis('off')
plt.axis()
plt.tight_layout(0,0,0)
plt.savefig("test.png")
plt.show()
def ReadWavFile():
from scipy.io import wavfile
# To add gain
''' audioFile = AudioSegment.from_wav('q/7548.123441052.wav')
audioFile += 20
samples = numpy.array(audioFile.get_array_of_samples().tolist())
samples_rate = 441000 '''
sample_rate, samples = wavfile.read('q/7548.123441052.wav')
# Spectrogram
fig,ax = plt.subplots(1)
fig.subplots_adjust(left=0, right=1, bottom=0, top=1)
ax.axis('off')
pxx, freqs, bins, im = plt.specgram(x=samples, Fs=sample_rate, noverlap=384, NFFT=512)
ax.axis('off')
fig.savefig('sp_xyz.png', frameon='false')
# Color Mesh
fig, ax = plt.subplots(1)
fig.subplots_adjust(left=0, right=1, bottom=0, top=1)
ax.axis('off')
frequencies, times, spectrogram = signal.spectrogram(samples, sample_rate)
plt.pcolormesh(times, frequencies, spectrogram)
plt.ylim(0, 8000)
# plt.xlim(0, 0.5)
ax.axis('off')
fig.savefig('test1.png', dpi = 100, frameon='false')
def ReadWavFile2():
from scipy.io import wavfile
audioFile = AudioSegment.from_wav('q/7548.12344105.wav')
audioFile += 0
samples = numpy.array(audioFile.get_array_of_samples().tolist())
sample_rate, _ = wavfile.read('q/7548.12344105.wav')
# Spectrogram
fig,ax = plt.subplots(1)
fig.subplots_adjust(left=0, right=1, bottom=0, top=1)
ax.axis('off')
pxx, freqs, bins, im = plt.specgram(x=samples, Fs=sample_rate, noverlap=384, NFFT=512)
ax.axis('off')
fig.savefig('sp_xyz.png', frameon='false')
# Color Mesh
fig, ax = plt.subplots(1)
fig.subplots_adjust(left=0, right=1, bottom=0, top=1)
ax.axis('off')
frequencies, times, spectrogram = signal.spectrogram(samples, sample_rate)
plt.pcolormesh(times, frequencies, spectrogram)
plt.ylim(0, 8000)
# plt.xlim(0, 0.5)
ax.axis('off')
fig.savefig('test2.png', dpi=100, frameon='false')
# Thread Class to Analyse Audio Segment
class analyseThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
global q
global keyPressedFlag
global keyPressed
keyPressedFlag = False
flagStart = False
while True:
lo.acquire()
while not q.empty():
f = q.get()
x = aT.fileClassification(f, "svmTaps", "svm")
q.task_done()
flagStart = True
if flagStart:
flagStart = False
onlyObj = [f for f in
listdir('.') if not isfile(join('.', f))]
# onlyObj.remove("drums")
onlyObj.remove("pyAudioAnalysis")
onlyObj.remove("images")
counter = len(onlyObj)
for i in range(0, counter):
if (float(x[1][i]) > 0.5) and (float(x[1][i]) < 0.99):
Sens = x[2][i]
else:
Sens = "NOISE"
if (Sens != "NOISE"):
print Sens
print x[1]
if keyPressedFlag: break
lo.release()
##############
##############
# MAIN FUNCTION:
def mainTap(ch):
recordKey().start()
onlyfiles = [f for f in listdir('.') if not isfile(join('.', f))]
# onlyfiles.remove("drums")
onlyfiles.remove("pyAudioAnalysis")
onlyfiles.remove("images")
global q
global keyPressedFlag
keyPressedFlag = False
q = Queue.Queue(0)
# ch = A (start Thread for drums) | B (Record new Data) | C (Start Thread for LaunchPad)
if (str(ch) == 'A'):
aT.featureAndTrain(onlyfiles, 1.0, 1.0, aT.shortTermWindow, aT.shortTermStep, "svm", "svmTaps", False)
startMode = True
elif (str(ch) == 'B'):
ch = 'x'
surfaceName = raw_input("Surface Name: ")
while (surfaceName != 'x'):
numberOfInputs = raw_input("Number of Data Points: ")
for i in range(0, int(numberOfInputs)):
print "Input " + str(i + 1)
addSurfacePoint(surfaceName)
surfaceName = raw_input("Surface Name: ")
if (startMode):
recordThread().start()
analyseThread().start()
analyseThread().start()
while not keyPressedFlag:
time.sleep(0.1)
def addSurfacePoint(surfacePointName):
print "Starting Record"
recordSurfacePoint(surfacePointName)
def recordSurfacePoint(surfacePointName):
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 0.9
randomFileName = str((random.random() * 100) * (random.random() * 100))
WAVE_OUTPUT_FILENAME = randomFileName + ".wav"
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
output=True,
frames_per_buffer=CHUNK)
print("* Recording in ")
print (".. 2")
time.sleep(0.2)
print (".. 1")
time.sleep(0.2)
print ("Tap!")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print("* done recording")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
if not os.path.exists(surfacePointName):
os.mkdir(str(surfacePointName))
os.rename(WAVE_OUTPUT_FILENAME, surfacePointName + "/" + WAVE_OUTPUT_FILENAME)
class recordKey(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
lis = keyboard.Listener(on_press=on_press)
lis.start() # start to listen on a separate thread
lis.join() # no this if main thread is polling self.keys