直接上代码:
必须的库:
from PyQt5 import QtMultimedia from PyQt5.QtCore import QUrl import time # 需要导入时间模块设置延时 import os
Demo 代码:
path = os.getcwd(); file = QUrl.fromLocalFile(path+"\xxxx.mp3") # 音频文件路径 content = QtMultimedia.QMediaContent(file) player = QtMultimedia.QMediaPlayer() player.setMedia(content) player.setVolume(50) player.play() time.sleep() # 设置延时等待音频播放结束
将代码加入qt系统中发现,
time.sleep() # 设置延时等待音频播放结束,即使另起一个线程,运行到播放音频代码段时仍然会造成其他线程的卡顿,而如果单独去掉time.sleep(),会出现音频无法播放的问题。
解决办法:
Qtimer定时器:用来定时更新数据
self.Music_timer = QTimer(self)
self.Music_timer.timeout.connect(self.fatigueMusic)
self.Music_timer.start(2000) # 2s更新数据
播放音频的函数:
def fatigueMusic(self):
path = os.getcwd();
while not self.framework.Music_result_queue.empty():
fatigue_result = self.framework.Music_result_queue.get()
# print("fatigue_result",fatigue_result)
if fatigue_result == 0:
file = QUrl.fromLocalFile(path + "\xx.mp3") # 音频文件路径
elif fatigue_result == 1:
file = QUrl.fromLocalFile(path + "\xxxx.mp3")# 音频文件路径
elif fatigue_result == 2:
file = QUrl.fromLocalFile(path + "\xxxx.mp3")# 音频文件路径
elif fatigue_result == 3:
file = QUrl.fromLocalFile(path + "\xxxx.mp3")# 音频文件路径
elif fatigue_result == 4:
file = QUrl.fromLocalFile(path + "\xx.mp3")# 音频文件路径
content = QtMultimedia.QMediaContent(file)
player = QtMultimedia.QMediaPlayer(self)
player.setMedia(content)
player.setVolume(50)
player.play()
可以看到相比Demo 代码,只修改了player = QtMultimedia.QMediaPlayer(self),运行,问题解决,且不阻塞其他进程的运行。