In this Python GUI article i want to show you How to Create Media Player in PyQt5, so when it comes to Python Programming Language, you different options for building GUI Applications, in this article we are going to learn How to Create Media Player in Python & PyQt5, first of all let’s talk about PyQt5.
What is PyQt5 ?
PyQt5 is Python binding for the Qt cross platform application framework. Using PyQt5 you can create desktop applications with graphical user interface (GUI) with Python programming language. PyQt5 is developed by Riverbank Computing and is licensed under the GPL and commercial licenses.
On the other hand Qt is popular framework for developing graphical user interfaces using C++ programming language, and PyQt5 provides access to all of Qt’s functionality, including support for widgets, layouts, graphics, multimedia and networking. it also provides Pythonic API for working with Qt, and PyQt5 makes it easy to create and manage GUIs in Python.
Some of the key features of PyQt5 include:
- Cross-platform support: PyQt5 allows you to create applications that run on multiple platforms, including Windows, macOS and Linux.
- Qt Designer integration: PyQt5 includes integration with Qt Designer, Qt Designer is a visual tool for designing and laying out GUIs.
- Good documentation: PyQt5 provides good documentation and examples, which make it easy to learn and use.
- Support for modern Python features: PyQt5 supports the latest features of Python such as type annotations, async/await and f-strings.
- Large community: PyQt5 has large and active community of developers, which provides support, guidance and contributions to the project.
so PyQt5 is often used in desktop application development for creating GUIs with functionalities, such as data visualization, multimedia playback and database integration. it is also often used in scientific and engineering applications for creating custom visualization and analysis tools, in this article you will see that how easily we can use multimedia module for creating of Media Player with Python & PyQt5.
What is PyQt5 Qt Multimedia ?
Qt Multimedia is an important module in PyQt5 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.
QMediaPlayer Class
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.
Note: Make sure that you download and install K-Lite Codec Pack Basic, if you don’t do this
then the media player will not play the video.
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 |
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 # Create a QWidget-based class to represent the application window class Window(QWidget): def __init__(self): super().__init__() # Set window properties such as title, size, and icon self.setWindowTitle("PyQt5 Media Player") self.setGeometry(350, 100, 700, 500) self.setWindowIcon(QIcon('player.png')) # Set window background color p =self.palette() p.setColor(QPalette.Window, Qt.black) self.setPalette(p) # Initialize the user interface self.init_ui() # Display the window self.show() # Initialize the user interface components def init_ui(self): # Create a QMediaPlayer object self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) # Create a QVideoWidget object to display video videowidget = QVideoWidget() # Create a QPushButton to open video files openBtn = QPushButton('Open Video') openBtn.clicked.connect(self.open_file) # Create a QPushButton to play or pause the video self.playBtn = QPushButton() self.playBtn.setEnabled(False) self.playBtn.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.playBtn.clicked.connect(self.play_video) # Create a QSlider for seeking within the video self.slider = QSlider(Qt.Horizontal) self.slider.setRange(0,0) self.slider.sliderMoved.connect(self.set_position) # Create a QLabel to display video information or errors self.label = QLabel() self.label.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum) # Create a QHBoxLayout for arranging widgets horizontally hboxLayout = QHBoxLayout() hboxLayout.setContentsMargins(0,0,0,0) # Add widgets to the QHBoxLayout hboxLayout.addWidget(openBtn) hboxLayout.addWidget(self.playBtn) hboxLayout.addWidget(self.slider) # Create a QVBoxLayout for arranging widgets vertically vboxLayout = QVBoxLayout() vboxLayout.addWidget(videowidget) vboxLayout.addLayout(hboxLayout) vboxLayout.addWidget(self.label) # Set the layout of the window self.setLayout(vboxLayout) # Set the video output for the media player self.mediaPlayer.setVideoOutput(videowidget) # Connect media player signals to their respective slots self.mediaPlayer.stateChanged.connect(self.mediastate_changed) self.mediaPlayer.positionChanged.connect(self.position_changed) self.mediaPlayer.durationChanged.connect(self.duration_changed) # Method to open a video file def open_file(self): filename, _ = QFileDialog.getOpenFileName(self, "Open Video") if filename != '': self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile(filename))) self.playBtn.setEnabled(True) # Method to play or pause the video def play_video(self): if self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.mediaPlayer.pause() else: self.mediaPlayer.play() # Method to handle changes in media player state (playing or paused) 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) ) # Method to handle changes in video position def position_changed(self, position): self.slider.setValue(position) # Method to handle changes in video duration def duration_changed(self, duration): self.slider.setRange(0, duration) # Method to set the video position def set_position(self, position): self.mediaPlayer.setPosition(position) # Method to handle errors in media playback def handle_errors(self): self.playBtn.setEnabled(False) self.label.setText("Error: " + self.mediaPlayer.errorString()) # Create the application instance app = QApplication(sys.argv) # Create the main window instance window = Window() # Run the application event loop 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.
Adding Full Screen and Volume Bar to Python Media Player
For adding full-screen functionality and a volume control bar to our existing code, we can follow these steps:
- Add a volume control slider (QSlider) and a full-screen button (QPushButton) to the user interface.
- Connect the volume control slider to a method that adjusts the volume of the media player.
- Connect the full-screen button to a method that toggles the window between full-screen and normal modes.
This is the complete code
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 |
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__() # Set window title, size, and icon self.setWindowTitle("Codeloop - PyQt5 Media Player") self.setGeometry(350, 100, 700, 500) self.setWindowIcon(QIcon('icon.png')) # Set window background color p = self.palette() p.setColor(QPalette.Window, Qt.black) self.setPalette(p) # Initialize the user interface self.init_ui() # Display the window self.show() def init_ui(self): # Create a QMediaPlayer object for media playback self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) # Create a QVideoWidget object to display video videowidget = QVideoWidget() # Create a QPushButton to open video files openBtn = QPushButton('Open Video') openBtn.clicked.connect(self.open_file) # Create a QPushButton to play or pause the video self.playBtn = QPushButton() self.playBtn.setEnabled(False) self.playBtn.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.playBtn.clicked.connect(self.play_video) # Create a QSlider for seeking within the video self.slider = QSlider(Qt.Horizontal) self.slider.setRange(0, 0) self.slider.sliderMoved.connect(self.set_position) # Create a QSlider for controlling the volume self.volumeSlider = QSlider(Qt.Horizontal) self.volumeSlider.setRange(0, 100) self.volumeSlider.setValue(50) # Set default volume self.volumeSlider.sliderMoved.connect(self.set_volume) # Create a QPushButton for toggling full-screen mode self.fullscreenBtn = QPushButton('Fullscreen') self.fullscreenBtn.clicked.connect(self.toggle_fullscreen) # Create a QHBoxLayout for arranging widgets horizontally hboxLayout = QHBoxLayout() hboxLayout.setContentsMargins(0, 0, 0, 0) # Add widgets to the QHBoxLayout hboxLayout.addWidget(openBtn) hboxLayout.addWidget(self.playBtn) hboxLayout.addWidget(self.slider) hboxLayout.addWidget(self.volumeSlider) hboxLayout.addWidget(self.fullscreenBtn) # Create a QVBoxLayout for arranging widgets vertically vboxLayout = QVBoxLayout() vboxLayout.addWidget(videowidget) vboxLayout.addLayout(hboxLayout) # Set the layout of the window self.setLayout(vboxLayout) # Set the video output for the media player self.mediaPlayer.setVideoOutput(videowidget) # Connect media player signals to their respective slots self.mediaPlayer.stateChanged.connect(self.mediastate_changed) self.mediaPlayer.positionChanged.connect(self.position_changed) self.mediaPlayer.durationChanged.connect(self.duration_changed) # Method to open a video file def open_file(self): filename, _ = QFileDialog.getOpenFileName(self, "Open Video") if filename != '': self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile(filename))) self.playBtn.setEnabled(True) # Method to play or pause the video def play_video(self): if self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.mediaPlayer.pause() else: self.mediaPlayer.play() # Method to handle changes in media player state (playing or paused) 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) ) # Method to handle changes in video position def position_changed(self, position): self.slider.setValue(position) # Method to handle changes in video duration def duration_changed(self, duration): self.slider.setRange(0, duration) # Method to set the video position def set_position(self, position): self.mediaPlayer.setPosition(position) # Method to set the volume of the media player def set_volume(self, volume): self.mediaPlayer.setVolume(volume) # Method to toggle full-screen mode def toggle_fullscreen(self): if self.isFullScreen(): self.showNormal() else: self.showFullScreen() # Create the application instance app = QApplication(sys.argv) # Create the main window instance window = Window() # Run the application event loop sys.exit(app.exec_()) |
Now, you have a volume control slider and a full-screen button added to your media player application. You can adjust the volume using the slider and switch between full-screen and normal modes using the full-screen button.
Run the code and this will be the result
Adding Pause and Stop Button to Python PyQt5 Media Player
For adding pause, play and stop buttons to the existing code, you can follow these steps:
- Create QPushButton instances for the pause, play and stop buttons.
- Connect each button to its respective method to handle the corresponding action (pausing, playing, stopping).
- Arrange the buttons in the user interface layout.
This is modified code with the pause, play and stop buttons added:
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 148 149 150 151 |
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__() # Set window title, size, and icon self.setWindowTitle("Codeloop - PyQt5 Media Player") self.setGeometry(350, 100, 700, 500) self.setWindowIcon(QIcon('icon.png')) # Set window background color p = self.palette() p.setColor(QPalette.Window, Qt.black) self.setPalette(p) # Initialize the user interface self.init_ui() self.show() def init_ui(self): # Initialize media player and video widget self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) videowidget = QVideoWidget() # Create buttons for controlling media playback openBtn = QPushButton('Open Video') openBtn.clicked.connect(self.open_file) self.playBtn = QPushButton('Play') self.playBtn.setEnabled(False) # Initialize as disabled self.playBtn.clicked.connect(self.play_video) self.pauseBtn = QPushButton('Pause') self.pauseBtn.setEnabled(False) # Initialize as disabled self.pauseBtn.clicked.connect(self.pause_video) self.stopBtn = QPushButton('Stop') self.stopBtn.setEnabled(False) # Initialize as disabled self.stopBtn.clicked.connect(self.stop_video) # Create sliders for seeking and volume control self.slider = QSlider(Qt.Horizontal) self.slider.setRange(0, 0) self.slider.sliderMoved.connect(self.set_position) self.volumeSlider = QSlider(Qt.Horizontal) self.volumeSlider.setRange(0, 100) self.volumeSlider.setValue(50) self.volumeSlider.sliderMoved.connect(self.set_volume) # Create button for toggling fullscreen mode self.fullscreenBtn = QPushButton('Fullscreen') self.fullscreenBtn.clicked.connect(self.toggle_fullscreen) # Create layout for arranging widgets horizontally hboxLayout = QHBoxLayout() hboxLayout.setContentsMargins(0, 0, 0, 0) hboxLayout.addWidget(openBtn) hboxLayout.addWidget(self.playBtn) hboxLayout.addWidget(self.pauseBtn) hboxLayout.addWidget(self.stopBtn) hboxLayout.addWidget(self.slider) hboxLayout.addWidget(self.volumeSlider) hboxLayout.addWidget(self.fullscreenBtn) # Create layout for arranging widgets vertically vboxLayout = QVBoxLayout() vboxLayout.addWidget(videowidget) vboxLayout.addLayout(hboxLayout) # Set the layout of the window self.setLayout(vboxLayout) self.mediaPlayer.setVideoOutput(videowidget) # Connect media player signals to their respective slots 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): # Open file dialog to select a video file filename, _ = QFileDialog.getOpenFileName(self, "Open Video") if filename != '': # Set the selected video file to the media player self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile(filename))) # Enable playback control buttons self.playBtn.setEnabled(True) self.pauseBtn.setEnabled(True) self.stopBtn.setEnabled(True) def play_video(self): # Start playback self.mediaPlayer.play() def pause_video(self): # Pause playback self.mediaPlayer.pause() def stop_video(self): # Stop playback self.mediaPlayer.stop() def mediastate_changed(self, state): # Update button states based on media player state if self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.playBtn.setEnabled(False) self.pauseBtn.setEnabled(True) self.stopBtn.setEnabled(True) else: self.playBtn.setEnabled(True) self.pauseBtn.setEnabled(False) self.stopBtn.setEnabled(False) def position_changed(self, position): # Update slider position based on current playback position self.slider.setValue(position) def duration_changed(self, duration): # Set slider range based on total duration of the video self.slider.setRange(0, duration) def set_position(self, position): # Set playback position based on slider value self.mediaPlayer.setPosition(position) def set_volume(self, volume): # Set playback volume based on slider value self.mediaPlayer.setVolume(volume) def toggle_fullscreen(self): # Toggle fullscreen mode if self.isFullScreen(): self.showNormal() else: self.showFullScreen() # Create the application instance app = QApplication(sys.argv) # Create the main window instance window = Window() # Run the application event loop sys.exit(app.exec_()) |
In this modified code:
- Three new buttons (playBtn, pauseBtn, stopBtn) are created for play, pause and stop actions.
- Each button is connected to its corresponding method (play_video, pause_video, stop_video) to handle the action.
- The mediastate_changed method is updated to enable/disable the buttons based on the media player state.
Run the code and this will be the result
How to Customize Appearance of Python PyQt5 Media Player?
For creating stylish and modern design for the buttons and sliders that be like a media player, you can use stylesheets in PyQt5. Below is an updated version of the code with customized stylesheets applied to the buttons and sliders:
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 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 |
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QVBoxLayout, QLabel, \ QSlider, QFileDialog from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent from PyQt5.QtMultimediaWidgets import QVideoWidget from PyQt5.QtGui import QIcon from PyQt5.QtCore import Qt, QUrl import sys class Window(QWidget): def __init__(self): super().__init__() # Set window properties such as title, size, and icon self.setWindowTitle("Codeloop - PyQt5 Media Player") self.setGeometry(350, 100, 700, 500) self.setWindowIcon(QIcon('icon.png')) # Initialize the user interface self.init_ui() self.show() def init_ui(self): # Initialize media player and video widget self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) videowidget = QVideoWidget() # Create buttons for controlling media playback openBtn = QPushButton('Open Video') openBtn.setStyleSheet( "QPushButton { background-color: #f0f0f0; border: 1px solid #707070; border-radius: 5px; padding: 5px; }" "QPushButton:hover { background-color: #e0e0e0; }" ) openBtn.clicked.connect(self.open_file) self.playBtn = QPushButton('Play') self.playBtn.setStyleSheet( "QPushButton { background-color: #f0f0f0; border: 1px solid #707070; border-radius: 5px; padding: 5px; }" "QPushButton:hover { background-color: #e0e0e0; }" ) self.playBtn.setEnabled(False) self.playBtn.clicked.connect(self.play_video) self.pauseBtn = QPushButton('Pause') self.pauseBtn.setStyleSheet( "QPushButton { background-color: #f0f0f0; border: 1px solid #707070; border-radius: 5px; padding: 5px; }" "QPushButton:hover { background-color: #e0e0e0; }" ) self.pauseBtn.setEnabled(False) self.pauseBtn.clicked.connect(self.pause_video) self.stopBtn = QPushButton('Stop') self.stopBtn.setStyleSheet( "QPushButton { background-color: #f0f0f0; border: 1px solid #707070; border-radius: 5px; padding: 5px; }" "QPushButton:hover { background-color: #e0e0e0; }" ) self.stopBtn.setEnabled(False) self.stopBtn.clicked.connect(self.stop_video) # Create sliders for seeking within the video and adjusting volume self.positionSlider = QSlider(Qt.Horizontal) self.positionSlider.setStyleSheet( "QSlider::groove:horizontal { height: 6px; background: #f0f0f0; border: 1px solid #707070; border-radius: 3px; }" "QSlider::handle:horizontal { background: #007bff; border: 1px solid #0056b3; width: 14px; margin: -5px 0px; border-radius: 7px; }" "QSlider::add-page:horizontal { background: white; }" "QSlider::sub-page:horizontal { background: #007bff; }" ) self.positionSlider.setRange(0, 0) self.positionSlider.sliderMoved.connect(self.set_position) self.volumeSlider = QSlider(Qt.Horizontal) self.volumeSlider.setStyleSheet( "QSlider::groove:horizontal { height: 6px; background: #f0f0f0; border: 1px solid #707070; border-radius: 3px; }" "QSlider::handle:horizontal { background: #007bff; border: 1px solid #0056b3; width: 14px; margin: -5px 0px; border-radius: 7px; }" "QSlider::add-page:horizontal { background: white; }" "QSlider::sub-page:horizontal { background: #007bff; }" ) self.volumeSlider.setValue(100) self.volumeSlider.setMaximum(100) self.volumeSlider.setToolTip("Volume") self.volumeSlider.valueChanged.connect(self.change_volume) # Create layout for arranging widgets horizontally hboxLayout = QHBoxLayout() hboxLayout.addWidget(openBtn) hboxLayout.addWidget(self.playBtn) hboxLayout.addWidget(self.pauseBtn) hboxLayout.addWidget(self.stopBtn) hboxLayout.addWidget(self.positionSlider) hboxLayout.addWidget(self.volumeSlider) # Create layout for arranging widgets vertically vboxLayout = QVBoxLayout() vboxLayout.addWidget(videowidget) vboxLayout.addLayout(hboxLayout) # Set the layout of the window self.setLayout(vboxLayout) self.mediaPlayer.setVideoOutput(videowidget) # Connect media player signals to their respective slots 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): # Open file dialog to select a video file filename, _ = QFileDialog.getOpenFileName(self, "Open Video") if filename != '': # Set the selected video file to the media player self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile(filename))) # Enable playback control buttons self.playBtn.setEnabled(True) self.pauseBtn.setEnabled(True) self.stopBtn.setEnabled(True) def play_video(self): # Start playback self.mediaPlayer.play() def pause_video(self): # Pause playback self.mediaPlayer.pause() def stop_video(self): # Stop playback self.mediaPlayer.stop() def mediastate_changed(self, state): # Update button states based on media player state if self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.playBtn.setEnabled(False) self.pauseBtn.setEnabled(True) self.stopBtn.setEnabled(True) else: self.playBtn.setEnabled(True) self.pauseBtn.setEnabled(False) self.stopBtn.setEnabled(False) def position_changed(self, position): # Update slider position based on current playback position self.positionSlider.setValue(position) def duration_changed(self, duration): # Set slider range based on total duration of the video self.positionSlider.setRange(0, duration) def set_position(self, position): # Set playback position based on slider value self.mediaPlayer.setPosition(position) def change_volume(self, volume): # Change media player volume based on slider value self.mediaPlayer.setVolume(volume) # Create the application instance app = QApplication(sys.argv) # Create the main window instance window = Window() # Run the application event loop sys.exit(app.exec_()) |
This code adds custom stylesheets to the buttons and slider, and it gives them more modern and nice appearance. You can adjust the colors and styles in the stylesheet strings to match your preferred design.
Run the complete code and this will be the result
FAQs:
How to build a media player in Python?
You can build a media player in Python using libraries such as PyQt5 or Pygame or TKinter, You can use these libraries for creating the graphical user interface (GUI) and managing media playback. This is a basic overview of the steps:
- Choose a GUI library: Select a suitable GUI library like PyQt5, Tkinter or Pygame for building the user interface of your media player.
- Design the user interface: Create widgets such as buttons, sliders and labels to control media playback and display information.
- Implement media playback: Use a media library like QtMultimedia or Pygame to handle the playback of audio and video files.
- Add functionality: Implement features like play, pause, stop volume control, seeking and fullscreen mode to enhance the user experience.
- Test and debug: Test your media player to ensure all functionalities work as expected and debug any issues that arise.
By following these steps and using the correct libraries, you can build a functional media player in Python.
How to play audio in PyQt5?
For playing audio in PyQt5, you can use the QMediaPlayer class from the QtMultimedia module.
How do I add a media player in PyQt5?
For adding a media player in PyQt5, you can use the QMediaPlayer and QVideoWidget classes from the QtMultimediaWidgets module.
Also you can check more Python GUI articles in the below links.
- Kivy GUI Development Tutorials
- Python TKinter GUI Development
- Psyide2 GUI Development
- wxPython GUI Development
- PyQt5 GUI Development Course
Subscribe and Get Free Video Courses & Articles in your Email
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?
I’m having the same problem
Hi, do you know how to insert an image into de pallete?? To make it seem as a video cover.