-
Notifications
You must be signed in to change notification settings - Fork 643
/
microphone.py
30 lines (28 loc) · 995 Bytes
/
microphone.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
import time
import numpy as np
import pyaudio
import config
def start_stream(callback):
p = pyaudio.PyAudio()
frames_per_buffer = int(config.MIC_RATE / config.FPS)
stream = p.open(format=pyaudio.paInt16,
channels=1,
rate=config.MIC_RATE,
input=True,
frames_per_buffer=frames_per_buffer)
overflows = 0
prev_ovf_time = time.time()
while True:
try:
y = np.fromstring(stream.read(frames_per_buffer, exception_on_overflow=False), dtype=np.int16)
y = y.astype(np.float32)
stream.read(stream.get_read_available(), exception_on_overflow=False)
callback(y)
except IOError:
overflows += 1
if time.time() > prev_ovf_time + 1:
prev_ovf_time = time.time()
print('Audio buffer has overflowed {} times'.format(overflows))
stream.stop_stream()
stream.close()
p.terminate()