Skip to content

[PyQt5] How to use QMediaPlayer module to play video

Last Updated on 2021-04-06 by Clay

PyQt5 can make us to develop many interesting tool in Python, there must be many people who want to develop some tools about video processing.

In PyQt5, you just need to use QMediaPlayer component.

Today I briefly record how to use PyQt5 to play videos.


QMediaPlayer

The simple playback code is just a few lines, and PyQt5 has been packaged quite lightly

# -*- coding: utf-8 -*-
import sys
from PyQt5.QtMultimedia import *
from PyQt5.QtMultimediaWidgets import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *


class VideoWindow(QMainWindow):
     def __init__(self):
         super(VideoWindow, self).__init__()
         self.setWindowTitle('QMediaPlayer TEST')
         self.resize(640, 480)

         # QMediaPlayer
         self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)
         self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile('test.mp4')))

         # Set widget
         self.videoWidget = QVideoWidget()
         self.videoWidget.setGeometry(self.pos().x(), self.pos().y(), self.width(), self.height())
         self.setCentralWidget(self.videoWidget)
         self.mediaPlayer.setVideoOutput(self.videoWidget)

         # Play
         self.mediaPlayer.play()


if __name__ == '__main__':
     app = QApplication([])
     window = VideoWindow()
     window.show()
     sys.exit(app.exec_())


Output:

I used to play a video of "bloodborn"

Since the code is quite short, I would overdo it with more explanations. Studying the code is probably the fastest way.

The only thing worth noting is that only the initialization of QMediaPlayer has not been able to display the picture of the movie, but the sound may have been heard.

We need to additionally use QVideoWidget() to initialize the playback interface and let our MainWindow use this as a Widget. Of course, you can customize the position and size of the video playback.

In addition, test.mp4 is my own video file, you can test your own video at will.

Leave a ReplyCancel reply

Exit mobile version