Search code examples
pythonqtpyqt5h.264qmediaplayer

Pyqt5 Mediaplayer in windows: limited to wmv?


I would like to have video preview in my Qt GUI and I was very happy to see that PyQt5 supports QMediaPlayer.

I found several basic examples here on SO, this one here below is just one:

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtMultimedia import *
from PyQt5.QtMultimediaWidgets import *

class VideoPlayer(QWidget):
    def __init__(self, parent=None):
        super(VideoPlayer, self).__init__(parent)
        videoItem = QGraphicsVideoItem()
        videoItem.setSize(QSizeF(640, 480))
        scene = QGraphicsScene(self)
        scene.addItem(videoItem)
        graphicsView = QGraphicsView(scene)
        layout = QVBoxLayout()
        layout.addWidget(graphicsView)
        self.setLayout(layout)
        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        self.mediaPlayer.setVideoOutput(videoItem)

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_L:
            print('loading')
            self.load()
        if e.key() == Qt.Key_P:
            print('playing')
            self.mediaPlayer.play()
        print('state: ' + str(self.mediaPlayer.state()))
        print('mediaStatus: ' + str(self.mediaPlayer.mediaStatus()))
        print('error: ' + str(self.mediaPlayer.error()))
        print('------------------------')


    def load(self):
        # H264 MPEG4 AVC not working
        file = 'C:/Users/Antonio/Videos/test.wmv'
        local = QUrl.fromLocalFile(file)
        media = QMediaContent(local)
        self.mediaPlayer.setMedia(media)

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    player = VideoPlayer()
    player.show()
    sys.exit(app.exec_())

The videos I would like to preview are generally encoded with H264 MPEG4 AVC and I can watch them on the pc using VLC for example. But when I try to open the same video with the script above, I get an InvalidMedia as error message.

I tried to convert the video in WMV+WMA using VLC and then it works as expected.

Reading a bit on the Qt Documentation (see here) I have the impression that on windows only WMF files are supported. Is this true?

Is there a possibility to extend QMediaPlayer to a larger family of formats via the installation of a codec bundle?

If yes, how can I make aware my pyqt5 installation where to find the relevant codecs?

Thanks in advance cheers


Solution

  • Qt uses the DirectShow backend on Windows, which, by defauilt, only supports the proprietary MS formats. For non-native formats, users must always install extra codecs, unless the applications they're using bundle them themselves. Qt completely relies on the capabilities of the platform backend, so you'll almost certainly have to install a third-party codec pack if you want to support a wider range of popular formats on Windows.