serial_audio_catcher/serial_audio.py

39 lines
915 B
Python
Raw Permalink Normal View History

import serial
import numpy as np
import wave
import time
SERIAL_PORT = '/dev/ttyACM0' # Adjust if needed
BAUD_RATE = 1500000
CHUNK_SIZE = 256 # frames per block
RATE = 16000 # sample rate
CHANNELS = 2 # stereo
# open serial
ser = serial.Serial(SERIAL_PORT, BAUD_RATE)
print("Recording 3 seconds of audio...")
frames = []
start = time.time()
try:
while time.time() - start < 3.0:
# 2 channels × 2 bytes per sample = 4 bytes per frame
data = ser.read(CHUNK_SIZE * 4)
if not data:
break
frames.append(data)
finally:
ser.close()
# write to wav
with wave.open("capture.wav", "wb") as wf:
wf.setnchannels(CHANNELS)
wf.setsampwidth(2) # 16bit samples = 2 bytes
wf.setframerate(RATE)
wf.writeframes(b"".join(frames))
print("Saved capture.wav")