-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathAudioRecorder.py
More file actions
44 lines (33 loc) · 1.32 KB
/
Copy pathAudioRecorder.py
File metadata and controls
44 lines (33 loc) · 1.32 KB
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
import threading
import queue
import numpy
import sounddevice as sd
import soundfile as sf
class AudioRecorder():
def __init__(self):
self.open = True
self.file_name = 'default_name' # This should be replaces with a value given in self.start()
self.channels = 1
self.q = queue.Queue()
# Get samplerate
device_info = sd.query_devices(2, 'input')
self.samplerate = int(device_info['default_samplerate'])
def callback(self, indata, frames, time, status):
# This is called (from a separate thread) for each audio block.
if status:
print(status, file=sys.stderr)
self.q.put(indata.copy())
def record(self):
with sf.SoundFile(self.file_name, mode='x', samplerate=self.samplerate,
channels=self.channels) as file:
with sd.InputStream(samplerate=self.samplerate,
channels=self.channels, callback=self.callback):
while(self.open == True):
file.write(self.q.get())
def stop(self):
self.open = False
def start(self, file_name, file_dir):
self.open = True
self.file_name = '{}/{}.wav'.format(file_dir, file_name)
audio_thread = threading.Thread(target=self.record)
audio_thread.start()