Play Video and Audio with Python PyQt5

In this PyQt5 article we want to learn about How to Play Video and Audio with Python PyQt5, so first of all about PyQt5, What is PyQt5?

 

 

What is PyQt5?

PyQt5 is popular Python library that allows you to create graphical user interfaces for desktop applications. in this article we want to explore how to play video and audio files using PyQt5.

 

 

How to Play Video and Audio with Python PyQt5

First of all we need to install PyQt5

 

 

Playing Audio Files with PyQt5

To play an audio file using PyQt5 we will use QMediaPlayer class. this class provides simple interface for playing audio files. this is an example.

Let’s break down what’s happening in this code:

  • We have imported necessary classes from PyQt5.
  • We have created QApplication instance to run our PyQt5 application.
  • We have create QMediaPlayer instance to play our audio file.
  • We have created QFileInfo instance to get information about our audio file.
  • We have created QUrl instance from the absolute file path of our audio file.
  • We set the media of our player to the QUrl instance.
  • We call the play method to start playing our audio file.
  • We call the exec_ method of our QApplication instance to run our application.

You can replace “path/to/audio/file.mp3” with the path to your own audio file.

 

 

 

Playing Video Files with PyQt5

Playing video files using PyQt5 is similar to playing audio files. main difference is that we need to create a widget to display the video. this is an example.

Let’s break down what’s happening in this code:

  • We have imported necessary classes from PyQt5.
  • We have created QApplication instance to run our PyQt5 application.
  • We have created QMediaPlayer instance to play our video file.
  • We have created QVideoWidget instance to display our video.
  • We have created QFileInfo instance to get information about our video file.
  • We have created QUrl instance from the absolute file path of our video file.
  • We set the media of our player to the QMediaContent instance.
  • We set the video output of our player to the QVideoWidget instance.
  • We create a QMainWindow instance and set the central widget to our QVideoWidget instance.
  • We show the main window.
  • We call the play method of our player to start playing our video file.
  • We call the exec_ method of our QApplication instance to run our application.

You can replace “path/to/video/file.mp4” with the path to your own video file.

 

 

 

Run the code and this will be the result

Play Video and Audio with Python PyQt5
Play Video and Audio with Python PyQt5

 

 

Subscribe and Get Free Video Courses & Articles in your Email

 

Leave a Comment

Share via
Copy link
Powered by Social Snap
×