In this Python GUI article i want to show you How to Create Media Player in PyQt5,
so in this article we are going to use QtMultimedia class, Qt Multimedia is an essential
module that handle multimedia content. It also provides necessary APIs to access the camera
and radio functionality. The included Qt Audio Engine provides types for 3D positional audio
playback and content management. check Documentation for Qt Multimedia. and from
QtMultimedia we are going to use QMediaPlayer and QMediaContent.
Also you can check more Python GUI articles in the below links.
1: Kivy GUI Development Tutorials
2: Python TKinter GUI Development
5: PyQt5 GUI Development Course
QMediaPlayer Class
The QMediaPlayer class is a high level media playback class. It can be used to playback
such content as songs, movies and internet radio. The content to playback is specified
as a QMediaContent object, which can be thought of as a main or canonical URL with
additional information attached. When provided with a QMediaContent playback may
be able to commence.
So now this is the complete code for Python How to Create Media Player in PyQt5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 | from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QVBoxLayout, QLabel, \ QSlider, QStyle, QSizePolicy, QFileDialog import sys from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent from PyQt5.QtMultimediaWidgets import QVideoWidget from PyQt5.QtGui import QIcon, QPalette from PyQt5.QtCore import Qt, QUrl class Window(QWidget): def __init__(self): super().__init__() self.setWindowTitle("PyQt5 Media Player") self.setGeometry(350, 100, 700, 500) self.setWindowIcon(QIcon('player.png')) p =self.palette() p.setColor(QPalette.Window, Qt.black) self.setPalette(p) self.init_ui() self.show() def init_ui(self): #create media player object self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) #create videowidget object videowidget = QVideoWidget() #create open button openBtn = QPushButton('Open Video') openBtn.clicked.connect(self.open_file) #create button for playing self.playBtn = QPushButton() self.playBtn.setEnabled(False) self.playBtn.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.playBtn.clicked.connect(self.play_video) #create slider self.slider = QSlider(Qt.Horizontal) self.slider.setRange(0,0) self.slider.sliderMoved.connect(self.set_position) #create label self.label = QLabel() self.label.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum) #create hbox layout hboxLayout = QHBoxLayout() hboxLayout.setContentsMargins(0,0,0,0) #set widgets to the hbox layout hboxLayout.addWidget(openBtn) hboxLayout.addWidget(self.playBtn) hboxLayout.addWidget(self.slider) #create vbox layout vboxLayout = QVBoxLayout() vboxLayout.addWidget(videowidget) vboxLayout.addLayout(hboxLayout) vboxLayout.addWidget(self.label) self.setLayout(vboxLayout) self.mediaPlayer.setVideoOutput(videowidget) #media player signals self.mediaPlayer.stateChanged.connect(self.mediastate_changed) self.mediaPlayer.positionChanged.connect(self.position_changed) self.mediaPlayer.durationChanged.connect(self.duration_changed) def open_file(self): filename, _ = QFileDialog.getOpenFileName(self, "Open Video") if filename != '': self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile(filename))) self.playBtn.setEnabled(True) def play_video(self): if self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.mediaPlayer.pause() else: self.mediaPlayer.play() def mediastate_changed(self, state): if self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.playBtn.setIcon( self.style().standardIcon(QStyle.SP_MediaPause) ) else: self.playBtn.setIcon( self.style().standardIcon(QStyle.SP_MediaPlay) ) def position_changed(self, position): self.slider.setValue(position) def duration_changed(self, duration): self.slider.setRange(0, duration) def set_position(self, position): self.mediaPlayer.setPosition(position) def handle_errors(self): self.playBtn.setEnabled(False) self.label.setText("Error: " + self.mediaPlayer.errorString()) app = QApplication(sys.argv) window = Window() sys.exit(app.exec_()) |
OK now let me describe the above code, first of all we have imported our required classes
from PyQt5 library. and these line of codes are for our window like title, icon, width and
height of the window.
1 2 3 | self.setWindowTitle("PyQt5 Media Player") self.setGeometry(350, 100, 700, 500) self.setWindowIcon(QIcon('player.png')) |
In here we are going to change the color of our window, we are going to use QPalette class,
so the QPalette class contains color groups for each widget state.
1 2 3 | p =self.palette() p.setColor(QPalette.Window, Qt.black) self.setPalette(p) |
OK now we are going to create the object of QMediaPlayer with QMediaContent.
1 2 | self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) videowidget = QVideoWidget() |
And now these are our widgets that we want to use in our media player like QPushButton,
QSlider, QLabel, QHBoxLayout and QVBoxLayout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | #create open button openBtn = QPushButton('Open Video') openBtn.clicked.connect(self.open_file) #create button for playing self.playBtn = QPushButton() self.playBtn.setEnabled(False) self.playBtn.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.playBtn.clicked.connect(self.play_video) #create slider self.slider = QSlider(Qt.Horizontal) self.slider.setRange(0,0) self.slider.sliderMoved.connect(self.set_position) #create label self.label = QLabel() self.label.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum) #create hbox layout hboxLayout = QHBoxLayout() hboxLayout.setContentsMargins(0,0,0,0) #set widgets to the hbox layout hboxLayout.addWidget(openBtn) hboxLayout.addWidget(self.playBtn) hboxLayout.addWidget(self.slider) #create vbox layout vboxLayout = QVBoxLayout() vboxLayout.addWidget(videowidget) vboxLayout.addLayout(hboxLayout) vboxLayout.addWidget(self.label) |
In here we are going to set our layout to the window and also we need to set the
QVideoWidget object to the media player, if you don’t do this you will not receive any output.
1 2 | self.setLayout(vboxLayout) self.mediaPlayer.setVideoOutput(videowidget) |
These are the signals for our media player, and we have connected these signals with the slot
that we are going to create.
1 2 3 | self.mediaPlayer.stateChanged.connect(self.mediastate_changed) self.mediaPlayer.positionChanged.connect(self.position_changed) self.mediaPlayer.durationChanged.connect(self.duration_changed) |
This method is for opening the directory, we are going to use QFileDialog for this, the
QFileDialog class enables a user to traverse the file system in order to select one or
many files or a directory.
1 2 3 4 5 6 | def open_file(self): filename, _ = QFileDialog.getOpenFileName(self, "Open Video") if filename != '': self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile(filename))) self.playBtn.setEnabled(True) |
In this method we are going to play the selected video, basically in the first we are checking
the state of media player, if our state is PlayingState, we are going to pause our media player,
in the else case we play our video in the media player.
1 2 3 4 5 6 | def play_video(self): if self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.mediaPlayer.pause() else: self.mediaPlayer.play() |
And now in this method we are checking the media state, because when a user want to pause
playing the video, we want to change the icon from play to pause and vice versa. also we are
using the built in icons from pyqt5.
1 2 3 4 5 6 7 8 9 10 11 12 | def mediastate_changed(self, state): if self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.playBtn.setIcon( self.style().standardIcon(QStyle.SP_MediaPause) ) else: self.playBtn.setIcon( self.style().standardIcon(QStyle.SP_MediaPlay) ) |
And these are the methods or slots that we have connected with the media player signals
at the top. the first and second methods are for automatically slider change, and the third
method is for if a user changes the slider, we have connected this method with the slider signal.
1 2 3 4 5 6 7 8 9 10 | def position_changed(self, position): self.slider.setValue(position) def duration_changed(self, duration): self.slider.setRange(0, duration) def set_position(self, position): self.mediaPlayer.setPosition(position) |
This is for handling the errors.
1 2 3 | def handle_errors(self): self.playBtn.setEnabled(False) self.label.setText("Error: " + self.mediaPlayer.errorString()) |
Also every PyQt5 application must create an application object. The sys.argv parameter is
a list of arguments from a command line.
1 | app = QApplication(sys.argv) |
Finally, we enter the mainloop of the application. The event handling starts from this point.
The mainloop receives events from the window system and dispatches them to the
application widgets.
1 | sys.exit(app.exec_()) |
So now run the complete code and this will be the result.

Also you can watch the complete video for this article.

Hi Parwiz,
I’ve watched many of your videos posted in YouTube, and I have one question regarding one of this How To Export File As PDF In PyQt5 #32, https://www.youtube.com/watch?v=XHlABoZWke0,
you mentioned that you can export the data from the QtextEdit to a PDF file, and I’d like to export but the info from a QTableWidget and when I type the code …
self.ui.tableWidget.document().print_(printer)
I got the following error:
line 52, in pdf
self.ui.tableWidget.document().print_(printer)
AttributeError: ‘QTableWidget’ object has no attribute ‘document’…
So my question is:
do you know which attribute should I need to use with QtableWidget?
I think after creating of the QTextDocument , you need to create a QTextCursor and add your document in TextCursor
Hmm in which part should I need to create the QTextDocument and also how do you create the textCursor, I have not seen that before, the funtion that I’m trying to call is the following…
def pdf(self):
fn, _= QFileDialog.getSaveFileName(self, “Export PDF”, None, “PDF files (.pdf);;All Files()”)
if fn != ”:
if QFileInfo(fn).suffix() == “”:fn += ‘.pdf’
printer = QPrinter(QPrinter.HighResolution)
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName(fn)
self.ui.tableWidget.document.print_(printer)
But as I mentioned before I got an error AttributeError: ‘QTableWidget’ object has no attribute ‘document’…,
So my question is is it possible to export the whole table content to a PDF with a similar funcion if so, how do yo create the function to do this¿?
Hi Parwiz,
I wonder if do you have an email where I can send you one question regarding one video related with PyQT?
I’ve already sent you a FB message but I didn’t receive an answer.
what is the question
I executed the exact code but after selecting the video file it throwing an error
“DirectShowPlayerService::doRender: Unresolved error code 0x80040266 (IDispatch error #102)”
I am using python 3.7.4(64 bit)
Please help me out.
can you tell me what is the version of your python and also what is your operating system
Hi,
i want to ask which python version you are using cuz i have run the same code but it is showing n video.
iam using python 3.6 and my pyqt5 version is 5.12
Hi Parwiz,
Thanks for the youtube tutorial and the source code, I copied and pasted the source code into python 3.7 and executed it but the video player didn’t work, I selected three videos which were .MP4 but none of them played after I clicked “Open video” and selected one, the media player just stayed as a black screen. Is there a restriction on the type of video format?
no there is no restriction, maybe there will be operating system problem, because i have used windows for this tutorial or maybe python version, the python version in this video was 3.6
Hi. Thanks for such a nice and detailed tutorial.
I have a question. How to load names of multiple image files using QFileDialog and add them to QListWidget. It’s like a playlist for music files but want to do with images. Thanks
Hello. Thanks for this tutorial.
Os is windows 10, python 3.6 and pyqt5 5.12 version. But video doesn’t play. What can I do?
Hello
You need to run your python code using terminal and check that what is the error, i think the main problem is on the codec, maybe you don’t have the required codec on the system
What is the required codec?
Hi, do you know how to insert an image into de pallete?? To make it seem as a video cover.