Search code examples
pythonqtpyqtpyqt5qmediaplayer

QMediaPlayer state not stopped when status changed to end of media


I have a problem using QMediaPlayer.mediaStatusChanged.

According to Qt5.7 documentation, when media status is changed to EndOfMedia, the QMediaPlayer state should be StoppedState:

Playback has reached the end of the current media. The player is in the StoppedState.

Qt5.7

However, the state is not stopped. Here is a sample that reproduces the issue:

import sys

from PyQt5 import QtWidgets
from PyQt5.QtCore import QUrl

from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent

class MediaPlayer(QMediaPlayer):
    default = 'test.mp3'

    def __init__(self):
        super(MediaPlayer, self).__init__()
        self.mediaStatusChanged[QMediaPlayer.MediaStatus].connect(self.media_status_changed)

        self.setup_media(self.default)

    def setup_media(self, media):
        url = QUrl.fromLocalFile(media)
        self.setMedia(QMediaContent(url))

    def media_status_changed(self, status):
        if status == QMediaPlayer.EndOfMedia:
            print(self.state() == QMediaPlayer.StoppedState) # I get False
            # self.state() is QMediaPlayer.PlayingState


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    m = MediaPlayer()
    m.play()
    sys.exit(app.exec_())

Does anyone face the same problem? I can fix the problem with a workaround but I think it may be a Qt problem.


Solution

  • I reported the issue to Qt as it seems to be a Windows only bug :

    Possible workarounds to fix the problem :

    1. Force stop before processing

      def media_status_changed(self, status):
          if status == QMediaPlayer.EndOfMedia:
              super(MediaPlayer, self).stop()
              # process
      
    2. Poll until getting StoppedState

      def media_status_changed(self, status):
          if status == QMediaPlayer.EndOfMedia:
              while not (self.state() == QMediaPlayer.StoppedState):
                  time.sleep(0.1)
              # process
      

    I will add here any update regarding the Qt issue.

    EDIT: issue updated and fixed in Qt v5.10.1