Play sound on button click in PyQt6

Question:

I am trying to create 2 buttons that would play a sound once and endlessly. But at this stage it is not possible to reproduce the sound at all. What am I doing wrong?

import sys
from PyQt6.QtCore import QUrl
from PyQt6.QtMultimedia import QMediaPlayer, QAudioOutput
from PyQt6.QtWidgets import QWidget, QPushButton, QVBoxLayout, QApplication


class SoundPlayer(QWidget):
    def __init__(self):
        super().__init__()

        filename = "sound.mp3"
        self.player = QMediaPlayer()
        self.audio_output = QAudioOutput()
        self.player.setAudioOutput(self.audio_output)
        self.player.setSource(QUrl.fromLocalFile(filename))
        self.audio_output.setVolume(50)
        # player.play()

        self.play_button = QPushButton('Play')
        self.play_endlessly_button = QPushButton('Play Endlessly')

        layout = QVBoxLayout()
        layout.addWidget(self.play_button)
        layout.addWidget(self.play_endlessly_button)
        self.setLayout(layout)

        self.play_button.clicked.connect(self.play_once)
        self.play_endlessly_button.clicked.connect(self.play_endlessly)

    def play_once(self):
        self.player.play()

    def play_endlessly(self):
        self.player.setLoops(QMediaPlayer.Loops.Infinite)
        self.player.play()

if __name__ == '__main__':
    app = QApplication([])
    widget = SoundPlayer()
    widget.show()
    sys.exit(app.exec())

Tried using the "play()" method of the QMediaPlayer class.
It is necessary that when the buttons are pressed, the sound is played once and endlessly according to the buttons.

Asked By: arachnoden

||

Answers:

You are using relative path "sound.mp3", relative path is resolved from current working directory, which is not always equals to source code directory and can be anything.

To verify that you can execute

print(os.path.realpath(os.getcwd()))

and

print(os.path.exists('sound.mp3'))

To fix that you can build absolute path using source directory as a base

filename = os.path.join(os.path.dirname(__file__), "sound.mp3")
Answered By: mugiseyebrows
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.