-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsoundrecorder.py
More file actions
57 lines (47 loc) · 2.09 KB
/
Copy pathsoundrecorder.py
File metadata and controls
57 lines (47 loc) · 2.09 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
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env python3
import sounddevice as sd
import soundfile as sf
import queue
import os
import threading
class Recorder:
def __init__(self):
self.is_recording = False
self.message_queue = queue.Queue()
self.rt = None
def record(self, filename):
if self.is_recording:
raise Exception("Already recording")
self.rt = self.RecorderThread(self.message_queue, outfile=filename)
self.rt.start()
self.is_recording = True
def stop_recording(self):
if not self.is_recording:
raise Exception("Not recording at the moment")
self.message_queue.put("plz stop or something...")
self.rt.join()
self.is_recording = False
class RecorderThread(threading.Thread):
def __init__(self, message_queue, sample_rate=44100, channels=1, q=queue.Queue(), outfile = "out.wav", ):
threading.Thread.__init__(self)
self.sample_rate = sample_rate
self.channels = channels
self.q = q
self.outfile = outfile
self.message_queue = message_queue
def run(self):
# Delete the output file if it exists
if os.path.isfile(self.outfile):
os.remove(self.outfile)
with sf.SoundFile(self.outfile, mode='x', samplerate=self.sample_rate, channels=self.channels) as file:
with sd.InputStream(samplerate=self.sample_rate, channels=self.channels, callback=self.recording_callback) as input_stream:
while self.message_queue.empty():
#print("queue empty")
file.write(self.q.get())
#print("got something in the queue")
input_stream.stop()
#print("streamed supposed to be stopped now")
def recording_callback(self, indata, frames, time, status):
#print("got something! frames: {} time: {}, status: {}".format(frames, time, status))
self.q.put(indata.copy())
return False