added python file for piping serial to speaker in windows
parent
5ec348c27b
commit
cb073b2d5b
37
main.py
37
main.py
|
|
@ -1,37 +0,0 @@
|
|||
import serial
|
||||
import pyaudio
|
||||
import numpy as np
|
||||
|
||||
SERIAL_PORT = '/dev/ttyACM0' # Change this to your serial port
|
||||
BAUD_RATE = 1500000
|
||||
CHUNK_SIZE = 256 # Number of frames in each block
|
||||
|
||||
p = pyaudio.PyAudio()
|
||||
|
||||
stream = p.open(format=pyaudio.paInt16,
|
||||
channels=2,
|
||||
rate=16000,
|
||||
output=True)
|
||||
|
||||
ser = serial.Serial(SERIAL_PORT, BAUD_RATE)
|
||||
|
||||
print("Streaming audio...")
|
||||
|
||||
try:
|
||||
while True:
|
||||
data = ser.read(CHUNK_SIZE * 4) # 2 channels × 2 bytes
|
||||
if not data:
|
||||
break
|
||||
|
||||
audio_data = np.frombuffer(data, dtype=np.int16)
|
||||
stream.write(audio_data.tobytes())
|
||||
|
||||
except KeyboardInterrupt:
|
||||
print("Stopping audio stream...")
|
||||
|
||||
finally:
|
||||
stream.stop_stream()
|
||||
stream.close()
|
||||
p.terminate()
|
||||
ser.close()
|
||||
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
import serial
|
||||
import pyaudio
|
||||
import numpy as np
|
||||
import struct
|
||||
|
||||
SERIAL_PORT = 'COM13' # Adjust to your port
|
||||
BAUD_RATE = 1500000
|
||||
BLOCK_SIZE = 512 # PCM bytes per block (128 stereo frames)
|
||||
MAGIC = 0xABCD # header marker
|
||||
RATE = 16000
|
||||
CHANNELS = 2
|
||||
|
||||
p = pyaudio.PyAudio()
|
||||
|
||||
stream = p.open(format=pyaudio.paInt16,
|
||||
channels=CHANNELS,
|
||||
rate=RATE,
|
||||
output=True)
|
||||
|
||||
ser = serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=1)
|
||||
|
||||
print("Streaming audio...")
|
||||
|
||||
try:
|
||||
while True:
|
||||
# Read 2‑byte header
|
||||
hdr = ser.read(2)
|
||||
if len(hdr) < 2:
|
||||
continue
|
||||
|
||||
(magic,) = struct.unpack('<H', hdr)
|
||||
if magic != MAGIC:
|
||||
# Not aligned, skip and retry
|
||||
continue
|
||||
|
||||
# Read PCM block
|
||||
data = ser.read(BLOCK_SIZE)
|
||||
if len(data) != BLOCK_SIZE:
|
||||
continue
|
||||
|
||||
# Convert to int16 and play
|
||||
audio_data = np.frombuffer(data, dtype=np.int16)
|
||||
stream.write(audio_data.tobytes())
|
||||
|
||||
except KeyboardInterrupt:
|
||||
print("Stopping audio stream...")
|
||||
|
||||
finally:
|
||||
stream.stop_stream()
|
||||
stream.close()
|
||||
p.terminate()
|
||||
ser.close()
|
||||
Loading…
Reference in New Issue