-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathaudiorecording.py
50 lines (40 loc) · 1.5 KB
/
audiorecording.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
import tempfile
import queue
import sys
import sounddevice as sd
import soundfile as sf
import numpy
assert numpy
def rec_audio(filename="audiorec_"):
q = queue.Queue()
def callback(indata, frames, time, status):
"""This is called (from a separate thread) for each audio block."""
if status:
print(status, file=sys.stderr)
q.put(indata.copy())
samplerate=None
#filename=None
device=None
channels=1
subtype=None
try:
if samplerate is None:
device_info = sd.query_devices(device, 'input')
# soundfile expects an int, sounddevice provides a float:
samplerate = int(device_info['default_samplerate'])
if filename is not None:
filename = tempfile.mktemp(prefix=filename,
suffix='.wav', dir='')
# Make sure the file is opened before recording anything:
with sf.SoundFile(filename, mode='x', samplerate=samplerate,
channels=channels, subtype=subtype) as file:
with sd.InputStream(samplerate=samplerate, device=device,
channels=channels, callback=callback):
print('#' * 50)
print('press Ctrl+C to stop the recording')
print('#' * 50)
while True:
file.write(q.get())
except KeyboardInterrupt:
print('\nRecording finished: ' + repr(filename))
return filename