首页 > 解决方案 > 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_()

标签: pythonpyqtpyqt5

解决方案


您的代码存在各种问题。

首先,您只能听到最后一个声音,因为在循环中您不断地覆盖 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_()

推荐阅读