Spaces:
Runtime error
Runtime error
import pyaudio | |
import wave | |
from pynput import keyboard | |
FORMAT = pyaudio.paInt16 | |
CHANNELS = 2 | |
RATE = 44100 | |
CHUNK = 1024 | |
RECORD_SECONDS = 5 | |
WAVE_OUTPUT_FILENAME = "output.wav" | |
frames = [] | |
def on_press(key): | |
global frames | |
if key.char == 'a': | |
print("Inside...") | |
# Start recording | |
audio = pyaudio.PyAudio() | |
stream = audio.open(format=FORMAT, channels=CHANNELS, | |
rate=RATE, input=True, | |
frames_per_buffer=CHUNK) | |
print("Recording audio...") | |
while True: | |
data = stream.read(CHUNK) | |
frames.append(data) | |
if keyboard.is_pressed('esc'): | |
break | |
stream.stop_stream() | |
stream.close() | |
audio.terminate() | |
def on_release(key): | |
if key == keyboard.Key.esc: | |
# Stop recording | |
audio = pyaudio.PyAudio() | |
stream = audio.open(format=FORMAT, channels=CHANNELS, | |
rate=RATE, input=True, | |
frames_per_buffer=CHUNK) | |
stream.stop_stream() | |
stream.close() | |
audio.terminate() | |
print("Finished recording audio.") | |
# Save recorded audio data to a .wav file | |
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb') | |
wf.setnchannels(CHANNELS) | |
wf.setsampwidth(audio.get_sample_size(FORMAT)) | |
wf.setframerate(RATE) | |
wf.writeframes(b''.join(frames)) | |
wf.close() | |
# Stop the listener | |
return False | |
# Start the listener | |
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener: | |
listener.join() | |