0

我正在运行 PyQt6。我有一个 QMainWindow,在一个小部件中有一个 QPushButton 和 QLineEdit。每次单击该按钮时,我都想播放一个声音,并且同时它会在我的行编辑中添加一个文本。我曾经playsound实现过这个效果,但是播放声音和添加文字时会有延迟。

我想消除这种延迟。我还发现在 PyQt4 中有 QSound 选项,但在 PyQt6 中不再存在。也许有替代品playsound

无论如何,这是我的代码:

import sys
from functools import cached_property, partial
from threading import Thread
from playsound import playsound
from PyQt6.QtCore import *
from PyQt6.QtGui import *
from PyQt6.QtWidgets import *

class Main(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Play Sound')
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        self.btn = QPushButton()
        self.lay = QHBoxLayout(central_widget)
        self.btn.setText('Play the Sound')
        self.lay.addWidget(self.btn)
        self.qline = QLineEdit()
        self.qline.setFixedHeight(35)
        self.lay.addWidget(self.qline)

        self.btn.clicked.connect(partial(self.buildExpression, 'X'))
        self.btn.clicked.connect(self.playsound)

    def line(self):
        return self.qline.text()
        
    def lineedit(self, text):
        self.qline.setText(text)
        self.qline.setFocus()

    def buildExpression(self, sub_exp):

        expression = self.line() + sub_exp
        self.lineedit(expression)

    def playsound(self):
        playsound('sound.mp3')

def background():
        while True:
            playsound('background.mp3')

def main():
    app = QApplication(sys.argv)
    run = Main()
    Thread(target=background, daemon=True).start()
    run.show()
    app.exec()

if __name__ == "__main__":
    main()
4

1 回答 1

0

好像:

playsound('sound.mp3', False)

成功了。如果我们想在再次单击按钮时再次启动声音(同时停止第一个声音),可能会有改进。

于 2021-07-01T14:19:33.163 回答