-
Notifications
You must be signed in to change notification settings - Fork 0
/
Microphone_loop.py
executable file
·71 lines (62 loc) · 2.14 KB
/
Microphone_loop.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
#! /usr/bin/env python
import alsaaudio
import numpy as np
import aubio
import threading
people = 0
def mic_loop():
# constants
samplerate = 44100
win_s = 2048
hop_s = win_s // 2
framesize = hop_s
print alsaaudio.cards()
print alsaaudio.mixers()
# set up audio input
recorder = alsaaudio.PCM(type=alsaaudio.PCM_CAPTURE)
#recorder = alsaaudio.PCM(type=PCM_CAPTURE, cardindex=1)
recorder.setperiodsize(framesize)
recorder.setrate(samplerate)
#recorder.setformat(alsaaudio.PCM_FORMAT_FLOAT_LE)
recorder.setchannels(1)
# create aubio pitch detection (first argument is method, "default" is
# "yinfft", can also be "yin", "mcomb", fcomb", "schmitt").
pitcher = aubio.pitch("default", win_s, hop_s, samplerate)
# set output unit (can be 'midi', 'cent', 'Hz', ...)
pitcher.set_unit("Hz")
# ignore frames under this level (dB)
pitcher.set_silence(-40)
print("Starting to listen, press Ctrl+C to stop")
count = 0
# main loop
while True:
# try:
# read data from audio input
_, data = recorder.read()
# convert data to aubio float samples
#samples = np.fromstring(data, dtype=aubio.float_type)
samples = np.fromstring(data, dtype=np.int16)
#print(len(samples),samples.min(),samples.max())
# pitch of current frame
#sample_test = np.hstack((samples,samples))
sample_test = np.array(samples,dtype=np.float32)
freq = pitcher(sample_test)[0]
# compute energy of current block
energy = np.sum(sample_test**2)/len(sample_test)
# do something with the results
if freq > 130 and freq < 200 and energy > 200000:
count = count + 1
if count > 1:
count = 0
people = 1
print("{:10.4f} {:10.4f}".format(freq,energy))
else:
people = 0
# except KeyboardInterrupt:
# print("Ctrl+C pressed, exiting")
# break
t = threading.Thread(target = mic_loop)
t.daemon = True
t.start()
while True:
print people