python - PyQt/ Python - 延迟播放音频文件列表
问题描述
我想循环一个数字列表并为每个数字播放一个相应的音频文件,每个声音之间有一个延迟,但是当我这样做时,它只播放列表中的最后一个声音。我正在使用 PyQt 设计器来构建我的应用程序。任何人都可以帮忙吗?到目前为止,我的代码如下:
from PyQt5 import uic, QtGui, QtMultimedia
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import random
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
app = QApplication([])
window = uic.loadUi("soundTask.ui")
numList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random.shuffle(numList)
def soundTimer():
def playSound():
QtMultimedia.QSound.play(f"soundFiles/{item}.wav")
window.numberTimer = QTimer()
window.numberTimer.setSingleShot(True)
window.numberTimer.start(3000)
window.numberTimer.timeout.connect(playSound)
for item in numList:
soundTimer()
window.show()
app.exec_()
解决方案
您的代码存在各种问题。
首先,您只能听到最后一个声音,因为在循环中您不断地覆盖 QTimer。每次发生这种情况时,前一个计时器都会被 Python 垃圾收集器删除,唯一“幸存”的计时器显然是最后一个计时器。
然后,虽然上述问题可能很容易解决,但代码的整个结构使它有点“笨拙”,因为它没有提供真正的“控制”或与实例的交互,任何扩展代码的尝试都会导致它更糟。
在下面的代码中,我假设您在 ui 文件中使用 QMainWindow,否则适当地更改继承的类 (QMainWindow)。
from PyQt5 import uic, QtGui, QtMultimedia
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import random
numList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random.shuffle(numList)
# Change to the appropriate class used in Designer, like QWidget or QDialog
class Window(QMainWindow):
def __init__(self):
super().__init__()
uic.loadUi('soundTask.ui', self)
self.soundFiles = []
for item in numList:
self.soundFiles.append(f"soundFiles/{item}.wav")
self.numberTimer = QTimer(singleShot=True)
self.numberTimer.timeout.connect(self.playNext)
self.numberTimer.start(3000)
self.currentSound = None
def playNext(self):
if not self.soundFiles:
return
if self.currentSound and not self.currentSound.isFinished():
# the previous sound is still playing, wait a bit longer
self.numberTimer.start(500)
self.currentSound = QtMultimedia.QSound(self.soundFiles.pop(0))
self.currentSound.play()
if self.soundFiles:
self.numberTimer.start(3000)
if __name__ == '__main__':
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
app = QApplication([])
window = Window()
window.show()
app.exec_()
推荐阅读
- julia - 我想找到对 Julia 的 0 起作用的数字 - 我的意思是最接近的 0
- apache-spark - 合并,合并火花数据框中的 2 列
- javascript - 套接字 io 问题
- android - 如何在更新进度条时在单独的线程上运行算法
- python - 窗口更改后 Tkinter 无法加载图像
- java - FileReader怎么没有flush,而FileWriter有flush?
- linux - 如何在不使用“write”命令的情况下获得可执行文件的输出?
- ckeditor - 内容安全策略编辑器
- javascript - CSS 继承之前的背景 rgba 值 EXCEPT alpha(不透明度)
- json - 用 jq(或 python3)解析 Maxmind JSON?