Very often PyQt5 QMediaPlayer displays an error message when opening a media file

63 views Asked by At

When I open the file, the console displays the error message

DirectShowPlayerService::doRender: Unresolved error code 0x80040218 (IDispatch error #24)

and the media file itself does not play. But if I try to open the media file again, it will most likely open and play without error. And this problem happens very often when opening media files (mp4, mp3, etc.). I am using: Windows 10 x64 1809 PyQt5 5.15.10 LAV Filters latest version from K-Lite Codec Pack.

After I noticed that the file was opening without error after reopening it after an error, I thought that the reason was that I had not terminated the previous media before opening the new one and the codecs simply did not have time to close from the previous file. I implemented a function that stops the playing media file and setVideoOutput to None. This function was run before opening the new file, but it did not produce any results. I also tried downloading an older version of LAV Filters, but without success. The function itself stops:

self.player.stop()
self.player.setMedia(QMediaContent())
self.player.setVideoOutput(None)

A minimal example of the complete code:

import sys
from PyQt5.QtCore import Qt, QUrl
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QPushButton, QFileDialog
from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent
from PyQt5.QtMultimediaWidgets import QVideoWidget

class Player(QMainWindow):
    def __init__(self, parent=None):
        super(Player, self).__init__(parent)
        
        self.media_player = QMediaPlayer(self)
        self.video_widget = QVideoWidget(self)

        self.media_player.setVideoOutput(self.video_widget)

        self.open_button = QPushButton("Open Media File")
        self.open_button.clicked.connect(self.open_file)

        layout = QVBoxLayout()
        layout.addWidget(self.video_widget)
        layout.addWidget(self.open_button)

        widget = QWidget(self)
        widget.setLayout(layout)
        self.setCentralWidget(widget)

    def open_file(self):
        file_dialog = QFileDialog()
        file_dialog.setAcceptMode(QFileDialog.AcceptOpen)
        if file_dialog.exec_() == QFileDialog.Accepted:
            selected_file = file_dialog.selectedUrls()[0].toString()
            self.stop_and_clear(selected_file)

    def stop_and_clear(self, selected_file):
        self.media_player.stop()
        self.media_player.setMedia(QMediaContent())
        self.media_player.setVideoOutput(None)

        self.set_and_play_file(selected_file)

    def set_and_play_file(self, selected_file):
        self.media_player.setMedia(QMediaContent(QUrl(selected_file)))
        self.media_player.setVideoOutput(self.video_widget)
        self.media_player.play()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    player = Player()
    player.show()
    sys.exit(app.exec_())
0

There are 0 answers