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

# 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 on_message(client, userdata, msg):
    print("Audio received")
    audio_data = msg.payload
    audio = AudioSegment.from_file(io.BytesIO(audio_data), format="wav")
    # 将音频保存为文件
    with open(output_file_path, 'wb') as f:
        f.write(audio_data)
    print(f"Audio saved as {output_file_path}")

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

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

if __name__ == "__main__":
    subscribe_audio()
