TakwayDisplayPlatform/mqtt/publish_audio_multithread.py

34 lines
886 B
Python

import paho.mqtt.client as mqtt
import threading
import time
# MQTT Broker信息
broker = '127.0.0.1'
port = 1883
topic = 'audio/test'
# 音频文件路径列表
audio_file_paths = ['tmp2.wav', 'tmp3.wav', 'tmp4.wav'] # 添加多个音频文件路径
def publish_audio(file_path):
client = mqtt.Client()
client.connect(broker, port)
with open(file_path, 'rb') as audio_file:
audio_data = audio_file.read()
client.publish(topic, audio_data)
client.disconnect()
print(f"Audio from {file_path} published successfully.")
if __name__ == "__main__":
threads = []
for file_path in audio_file_paths:
thread = threading.Thread(target=publish_audio, args=(file_path,))
thread.start()
threads.append(thread)
time.sleep(1) # 可选:给每个线程一些间隔时间
for thread in threads:
thread.join()