0

I'm running PyQt6. I have a QMainWindow with one QPushButton and QLineEdit in a widget. I want to play a sound every time I click the button, and simuatenously it adds a text to my line edit. I used playsound to achieve this effect, but there's a delay when the sound is played and the text is added.

I want to remove that delay. I have also found that there were QSound options way back in PyQt4 but it doesn't exist in PyQt6 anymore. Maybe there are alternatives to playsound?

Anyway, here is my code:

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()
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
JA23Z
  • 25
  • 5

1 Answers1

1

Looks like:

playsound('sound.mp3', False)

did the trick. There may be improvements though if we want to start the sound again(while stopping the first) when clicking the button again.

JA23Z
  • 25
  • 5