Debtanu Gupta
Debtanu Gupta

Reputation: 77

Why in PyQt5 mp3 file loop isn't working?

I make an application which will ring an mp3 for 100 times. But it works only for 1 time. Why this is happening?

Here is the code

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtMultimedia import *
from PyQt5 import QtCore, QtMultimedia
from PyQt5.QtGui import *
import sys


class AlarmWindow(QDialog):
    def __init__(self, alarmName, alarmTime, alarmTone):
        super().__init__()

        self.setWindowTitle = alarmName
        self.top, self.left = 100, 50
        self.width, self.height = 600, 350
        self.setFixedWidth(600)
        self.setFixedHeight(350)
        self.icon = "icons\\alarm.ico"
  
        self.url = QtCore.QUrl.fromLocalFile(alarmTone)
        self.content = QtMultimedia.QMediaContent(self.url)
        self.player = QtMultimedia.QMediaPlayer()
        self.player.setMedia(self.content)
        self.play()
        self.show()

    def play(self):
        for i in range(100):
            self.player.play()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = AlarmWindow("Name", "7:55 PM", "basic.mp3")
    app.exec()

Upvotes: 1

Views: 109

Answers (1)

mkrieger1
mkrieger1

Reputation: 23117

self.player.play() does not block until the mp3 has finished playing. Calling it 100 times in a row will do nothing while it is still playing.

You could use the stateChanged signal to be notified when the player has finished playing, and then start it again with a callback.

It should work something like this:

def play(self):
    played = 0

    def restart(state):
        nonlocal played
        if state != QMediaPlayer.StoppedState:
            return
        if played == 100:
            return
        played += 1
        self.player.play()

    self.player.stateChanged.connect(restart)
    self.player.play()

Upvotes: 6

Related Questions