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()
