import pyaudio
import wave
import threading
import time
class Recorder:
def __init__(self, filename='recording.wav', chunk=1024, format=pyaudio.paInt16, channels=2, rate=44100):
self.filename = filename
self.chunk = chunk
self.format = format
self.channels = channels
self.rate = rate
self.frames = []
self.p = pyaudio.PyAudio()
self.is_recording = False
self.record_thread = None
def start_recording(self):
if self.is_recording:
print("Recording is already in progress.")
return
print("Recording started.")
self.is_recording = True
self.frames = []
self.stream = self.p.open(format=self.format,
channels=self.channels,
rate=self.rate,
input=True,
frames_per_buffer=self.chunk)
self.record_thread = threading.Thread(target=self._record)
self.record_thread.start()
def stop_recording(self):
if not self.is_recording:
print("No recording in progress.")
return
print("Recording stopped.")
self.is_recording = False
self.stream.stop_stream()
self.stream.close()
self.record_thread.join()
wf = wave.open(self.filename, 'wb')
wf.setnchannels(self.channels)
wf.setsampwidth(self.p.get_sample_size(self.format))
wf.setframerate(self.rate)
wf.writeframes(b''.join(self.frames))
wf.close()
def _record(self):
while self.is_recording:
data = self.stream.read(self.chunk)
self.frames.append(data)
if __name__ == "__main__":
filename = input("Enter the filename to save recording (default is 'recording.wav'): ").strip() or 'recording.wav'
recorder = Recorder(filename=filename)
print("Press 'r' to start recording, 's' to stop recording, and 'q' to quit.")
while True:
command = input("> ").strip().lower()
if command == 'r':
recorder.start_recording()
elif command == 's':
recorder.stop_recording()
print("Recording saved to", filename)
elif command == 'q':
if recorder.is_recording:
recorder.stop_recording()
print("Recording saved to", filename)
break
else:
print("Invalid command. Please enter 'r' to start recording, 's' to stop recording, or 'q' to quit.")
time.sleep(0.1) # sleep to avoid high CPU usage in the loop