import socket
import psutil
import pyaudio

# This streamer can be used to preview assistant audio for example for presentation.
# For this you have to set OBS to following ffmpeg streaming settings:
# 48khz
# stereo
# PCM signed 16bit little endian



# get local ip adress of main network interface
interfaces = psutil.net_if_addrs()
for interface, addrs in interfaces.items():
    if "Wi-Fi" in interface:
        print("name: ", interface)
        for addr in addrs:
            if addr.family == socket.AF_INET:
                UDP_IP = addr.address
                print("ip: ", UDP_IP)
                break
        break

UDP_PORT = 8081

print("port: ", UDP_PORT)

# PyAudio parameters
CHANNELS = 2

# 16-bit audio
WIDTH = 2
RATE = 48000

BUFFER_SIZE = 2048


# Create a UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))

# Initialize PyAudio
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(WIDTH),
                channels=CHANNELS,
                rate=RATE,
                output=True)

print("Stream started. Press Ctrl+C to stop.")

try:
    while True:
        # Receive audio data
        data, addr = sock.recvfrom(BUFFER_SIZE)
        
        # Play the audio data
        stream.write(data)

except KeyboardInterrupt:
    print("\nStreaming stopped.")

finally:
    # Close the stream and socket
    stream.stop_stream()
    stream.close()
    p.terminate()
    sock.close()
