如何让QPushButton在向我的QLineEdit添加文本的同时播放声音



我正在运行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()

看起来像:

playsound('sound.mp3', False)

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

最新更新