import paho.mqtt.client as mqtt
from pydub import AudioSegment
import io
import threading

# MQTT Broker信息
broker = '127.0.0.1'
port = 1883
topic = 'audio/test'
output_file_path = 'received_audio.wav'

def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    client.subscribe(topic)

def handle_audio(audio_data):
    # 将音频保存为文件
    with open(output_file_path, 'wb') as f:
        f.write(audio_data)
    print(f"Audio saved as {output_file_path}")

def on_message(client, userdata, msg):
    print("Audio received")
    audio_data = msg.payload
    # 使用线程来处理音频
    audio_thread = threading.Thread(target=handle_audio, args=(audio_data,))
    audio_thread.start()

def subscribe_audio():
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message

    client.connect(broker, port)
    client.loop_forever()

def mqtt_thread():
    subscribe_audio()

if __name__ == "__main__":
    mqtt_thread = threading.Thread(target=mqtt_thread)
    mqtt_thread.start()
