Pyqt5 designer установить windows

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:

  1. Cross-platform support: PyQt5 allows you to create applications that run on multiple platforms, including Windows, macOS and Linux.
  2. Qt Designer integration: PyQt5 includes integration with Qt Designer, Qt Designer is a visual tool for designing and laying out GUIs.
  3. Good documentation: PyQt5 provides good documentation and examples, which make it easy to learn and use.
  4. Support for modern Python features: PyQt5 supports the latest features of Python such as type annotations, async/await and f-strings.
  5. 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.

  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.

  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.

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.

  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.

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.

    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.

    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.

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.

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.

    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. 

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. 

So now run the complete code and this will be the result.

Python How to Create Media Player in PyQt5

Python How to Create Media Player in PyQt5

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:

  1. Add a volume control slider (QSlider) and a full-screen button (QPushButton) to the user interface.
  2. Connect the volume control slider to a method that adjusts the volume of the media player.
  3. 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

How to Create Media Player in Python

How to Create Media Player in Python

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:

  1. Create QPushButton instances for the pause, play and stop buttons.
  2. Connect each button to its respective method to handle the corresponding action (pausing, playing, stopping).
  3. 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

Media Player in Python

Media Player in Python

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

Customize PyQt5 Media Player

Customize PyQt5 Media Player

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:

  1. Choose a GUI library: Select a suitable GUI library like PyQt5, Tkinter or Pygame for building the user interface of your media player.
  2. Design the user interface: Create widgets such as buttons, sliders and labels to control media playback and display information.
  3. Implement media playback: Use a media library like QtMultimedia or Pygame to handle the playback of audio and video files.
  4. Add functionality: Implement features like play, pause, stop volume control, seeking and fullscreen mode to enhance the user experience.
  5. 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

MediaPlayer

A simple media player for macOS and Windows, based on Python 3, PyQt5 (portable to PyQt6 or PySide6) and a custom widget called VideoWidget that uses native system multimedia frameworks directly (AVFoundation in macOS, DirectShow and LAV Filters in Windows).

Supported video containers

  • Windows: 3gp asf asx avi dv f4v flv gif m2ts m4v mkv mov mp4 mpeg mts mxf ogv rm ts vob webm wmv wtv
  • macOS: 3gp avi m2ts m2v m4v mov mp4 mpg mpeg mts mxf ts vob
    (mxf only when free Pro Video Formats are installed)

Supported audio containers

  • Windows: aac ac3 aiff ape caf flac mp3 ogg sox wav
  • macOS: aac ac3 aiff caf flac mp3 wav

Supported video codecs (selection)

  • Windows: bink cinepak dirac dvvideo flv1 (sorenson spark) fraps gif h264 hap1 hap5 hapy hevc indeo mjpeg mpeg1 mpeg2 mpeg4 msrle msvideo1 prores422 prores4444 qtrle theora vp4 vp6 vp7 wmv12 wmv3
  • macOS: dvvideo h264 hevc mjpeg mpeg1 mpeg2 prores422 prores4444
    (+ Pro Video Formats, if installed)

Supported audio codecs (selection)

  • Windows: aac ac3 alac dts flac mp2 mp3 nellymoser opus pcm realaudio truespeech vorbis wavpack wma
  • macOS: aac ac3 alac flac mp2 mp3 pcm

VideoWidget’s API

Signals

mediaReady                  -> bool success
mousePressed                -> None
doubleClicked               -> None

Properties

filename                    -> the currently loaded file ur URL (full path)

Methods

load_media(filename: str)
close_media()
step(steps: int)            -> step <steps> frames forward, or back if <steps> is negative
get_natural_size()          -> returns tuple (width, height) or None
get_duration()              -> returns seconds as float, or 0 if there is no duration
get_fps()                   -> returns fps as float, or None if there is no framerate
has_video()                 -> returns bool (True or False)
has_audio()                 -> returns bool (True or False)
get_volume()                -> returns volume as float in range 0..1
set_volume(volume: float)   -> set volume as float in range 0..1
set_muted(flag: bool)       -> True mutes, False unmutes
seek_to_time(sec: float)    -> seek to time in seconds as float
get_time()                  -> returns current time in seconds as float (or None)
play()
pause()
toggle_playback()           -> returns True if player now playing, otherwise False

Notes

You don’t have to connect to signals mousePressed and doubleClicked, but you always have to connect to signal mediaReady, since loading a media file is asynchronous in macOS/AVFoundation. So when loading a file with load_media(), you always have to wait until mediaReady is emitted, and if ‘success’ was True, you can go on and now do stuff with the loaded media, if it was False then something went wrong, i.e. the file couldn’t be loaded.

Screenshots

MediaPlayer in Windows 11

MediaPlayer in Windows 11

MediaPlayer in macOS 13

MediaPlayer in macOS 13

This article explains how to make a Video Player in PyQt5.

One of PyQt5’s most unique widgets (in my opinion anyway) is the QMediaPlayer with it’s ability to display videos in a PyQt5 GUI. Since it’s a pretty complex task, you’ll need other classes and widgets from the QMultimedia class (we’ll explain all these).

In any case, it’s cool to know how to so that’s something. It looks pretty good and modern looking too so that’s another bonus. By the end of this article we’ll show you an implementation that looks almost as good as fully fledged Video players like VLC.

In the event that the Video does not load and play correctly, there must be an Issue with your Graphic drivers or something similar. I experienced issues on my Laptop (an APU) with an AMD Vega graphic card, so I switch over to my PC which had an NVIDIA card and it worked just fine.


Playing Videos in PyQt5

In this section we’ll discuss how to get a simple video player up and running. It’s a very bare bone video player with only the ability to play/pause videos and select a file.

Clicking the play button once will start the Video and clicking it again will pause the Video.

from PyQt5.QtCore import QDir, Qt, QUrl
from PyQt5.QtMultimedia import QMediaContent, QMediaPlayer
from PyQt5.QtMultimediaWidgets import QVideoWidget
from PyQt5.QtWidgets import (QMainWindow, QWidget, QPushButton, QApplication,
                             QLabel, QFileDialog, QStyle, QVBoxLayout)
import sys

class VideoPlayer(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("PyQt5 Video Player") 

        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        videoWidget = QVideoWidget()

        self.playButton = QPushButton()
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play)

        self.openButton = QPushButton("Open Video")   
        self.openButton.clicked.connect(self.openFile)

        widget = QWidget(self)
        self.setCentralWidget(widget)

        layout = QVBoxLayout()
        layout.addWidget(videoWidget)
        layout.addWidget(self.openButton)
        layout.addWidget(self.playButton)

        widget.setLayout(layout)
        self.mediaPlayer.setVideoOutput(videoWidget)

    def openFile(self):
        fileName, _ = QFileDialog.getOpenFileName(self, "Open Movie",
                QDir.homePath())

        if fileName != '':
            self.mediaPlayer.setMedia(
                    QMediaContent(QUrl.fromLocalFile(fileName)))

    def play(self):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.mediaPlayer.pause()
        else:
            self.mediaPlayer.play()


app = QApplication(sys.argv)
videoplayer = VideoPlayer()
videoplayer.resize(640, 480)
videoplayer.show()
sys.exit(app.exec_())

It’s alot of code, so we’ll try explaining it line by line. For explanations regarding the non-Video Player code, please refer to our PyQt5 tutorial series where all other widgets are explained.

        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        videoWidget = QVideoWidget()

In the first line we create our MediaPlayer object by passing the required parameters in QMediaPlayer. In the second we create a video widget using QVideoWidget.

self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play)

The first line is actually an optional one simply for the “look” of the “play button we’ll be creating. This line gives it that special triangular icon that all play buttons have. The second line connects the button to the play function. More on the play function later.

        self.openButton = QPushButton("Open Video")   
        self.openButton.clicked.connect(self.openFile)

This the “open button” which will allow the user to select a video of his choice from his computer. We connect this button to the function called openFile where the File dialog code is stored.

    self.mediaPlayer.setVideoOutput(videoWidget)

Remember that video widget we created earlier? We need to pass that into our MediaPlayer Video output function. Imagine a QMediaPlayer as the actual supporting software around the video, and the QVideoWidget is the actual PyQt5 video output.

    def openFile(self):
        fileName, _ = QFileDialog.getOpenFileName(self, "Open Movie",
                QDir.homePath())

        if fileName != '':
            self.mediaPlayer.setMedia(
                    QMediaContent(QUrl.fromLocalFile(fileName)))

This function is responsible for creating a File Dialog which allows the user to pick a local video file from his computer. The filepath of the video file is returned which we will be using to set the QMediaContent. The setMedia() function is used to insert the MediaContent into the MediaPlayer object you created.

    def play(self):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.mediaPlayer.pause()
        else:
            self.mediaPlayer.play()

The play function is pretty simple. If the Video is not playing, the Video will begin once the play function is called. If the Video is playing, the play function will pause the video.

You could make this even simpler if you wanted by removing the play button and the file dialog. However, this would come at the cost of two things. The loss of the ability to play and pause at will and the ability to select the file to be played.

There’s no (significant) limit to the size of the video that you load up, as I tested a full length (2 hours 20 min) movie with QMediaPlayer and it worked perfectly.


Full Video Player in PyQt5

Below is the full implementation of a proper Video Player in PyQt5. There is only really one big change, which is the addition of a slider bar. Changing the position of this Slider will change the current scene playing on the Screen, just like a regular video player.

Another change is the addition of an error handling system. In the event the Video File you loaded was unable to run or some error occurred, an error message will display.

from PyQt5.QtCore import QDir, Qt, QUrl
from PyQt5.QtMultimedia import QMediaContent, QMediaPlayer
from PyQt5.QtMultimediaWidgets import QVideoWidget
from PyQt5.QtWidgets import (QApplication, QFileDialog, QHBoxLayout, QLabel,
        QPushButton, QSizePolicy, QSlider, QStyle, QVBoxLayout, QWidget)
from PyQt5.QtWidgets import QMainWindow,QWidget, QPushButton, QAction
from PyQt5.QtGui import QIcon
import sys

class VideoPlayer(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("PyQt5 Video Player") 

        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)

        videoWidget = QVideoWidget()

        self.playButton = QPushButton()
        self.playButton.setEnabled(False)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play)

        self.positionSlider = QSlider(Qt.Horizontal)
        self.positionSlider.setRange(0, 0)
        self.positionSlider.sliderMoved.connect(self.setPosition)

        self.error = QLabel()
        self.error.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)

        openButton = QPushButton("Open Video")   
        openButton.setToolTip("Open Video File")
        openButton.setStatusTip("Open Video File")
        openButton.setFixedHeight(24)
        openButton.clicked.connect(self.openFile)


        # Create a widget for window contents
        wid = QWidget(self)
        self.setCentralWidget(wid)

        # Create layouts to place inside widget
        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(0, 0, 0, 0)
        controlLayout.addWidget(self.playButton)
        controlLayout.addWidget(self.positionSlider)

        layout = QVBoxLayout()
        layout.addWidget(videoWidget)
        layout.addLayout(controlLayout)
        layout.addWidget(self.error)
        layout.addWidget(openButton)

        # Set widget to contain window contents
        wid.setLayout(layout)

        self.mediaPlayer.setVideoOutput(videoWidget)
        self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.mediaPlayer.positionChanged.connect(self.positionChanged)
        self.mediaPlayer.durationChanged.connect(self.durationChanged)
        self.mediaPlayer.error.connect(self.handleError)

    def openFile(self):
        fileName, _ = QFileDialog.getOpenFileName(self, "Open Movie",
                QDir.homePath())

        if fileName != '':
            self.mediaPlayer.setMedia(
                    QMediaContent(QUrl.fromLocalFile(fileName)))
            self.playButton.setEnabled(True)

    def exitCall(self):
        sys.exit(app.exec_())

    def play(self):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.mediaPlayer.pause()
        else:
            self.mediaPlayer.play()

    def mediaStateChanged(self, state):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.playButton.setIcon(
                    self.style().standardIcon(QStyle.SP_MediaPause))
        else:
            self.playButton.setIcon(
                    self.style().standardIcon(QStyle.SP_MediaPlay))

    def positionChanged(self, position):
        self.positionSlider.setValue(position)

    def durationChanged(self, duration):
        self.positionSlider.setRange(0, duration)

    def setPosition(self, position):
        self.mediaPlayer.setPosition(position)

    def handleError(self):
        self.playButton.setEnabled(False)
        self.error.setText("Error: " + self.mediaPlayer.errorString())


app = QApplication(sys.argv)
videoplayer = VideoPlayer()
videoplayer.resize(640, 480)
videoplayer.show()
sys.exit(app.exec_())

An screen shot from a movie that I tested in QMediaPlayer.

PyQt5 Video Player


This marks the end of the PyQt5 Video Player with QMediaPlayer article. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article content can be asked in the comments section below.

pyqt5 video widget

In this article you’ll see the code to create a video player with PyQT5.
It contains a menu bar for opening the video file.

PyQt5 supports multimedia, including a video widget: QVideoWidget. This is used in combination with the class QMediaPlayer.

The QMediaPlayer class has all kinds of properties that you may know from video players: audioAvailable, duration, position, volume and a few others.

Related course: Create PyQt Desktop Appications with Python (GUI)

Introduction

We create a window (QMainWindow) that contains a widget for its contents (QWidget).
Then we add the videowidget and control widgets.

pyqt video player

videoWidget = QVideoWidget()

self.playButton = QPushButton()
self.playButton.setEnabled(False)
self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
self.playButton.clicked.connect(self.play)

The player will only play a video, in this example we don’t use back buttons, stop buttons.

Download PyQt Examples

The complete code below:




from PyQt5.QtCore import QDir, Qt, QUrl
from PyQt5.QtMultimedia import QMediaContent, QMediaPlayer
from PyQt5.QtMultimediaWidgets import QVideoWidget
from PyQt5.QtWidgets import (QApplication, QFileDialog, QHBoxLayout, QLabel,
QPushButton, QSizePolicy, QSlider, QStyle, QVBoxLayout, QWidget)
from PyQt5.QtWidgets import QMainWindow,QWidget, QPushButton, QAction
from PyQt5.QtGui import QIcon
import sys

class VideoWindow(QMainWindow):

def __init__(self, parent=None):
super(VideoWindow, self).__init__(parent)
self.setWindowTitle("PyQt Video Player Widget Example - pythonprogramminglanguage.com")

self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)

videoWidget = QVideoWidget()

self.playButton = QPushButton()
self.playButton.setEnabled(False)
self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
self.playButton.clicked.connect(self.play)

self.positionSlider = QSlider(Qt.Horizontal)
self.positionSlider.setRange(0, 0)
self.positionSlider.sliderMoved.connect(self.setPosition)

self.errorLabel = QLabel()
self.errorLabel.setSizePolicy(QSizePolicy.Preferred,
QSizePolicy.Maximum)


openAction = QAction(QIcon('open.png'), '&Open', self)
openAction.setShortcut('Ctrl+O')
openAction.setStatusTip('Open movie')
openAction.triggered.connect(self.openFile)


exitAction = QAction(QIcon('exit.png'), '&Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
exitAction.triggered.connect(self.exitCall)


menuBar = self.menuBar()
fileMenu = menuBar.addMenu('&File')

fileMenu.addAction(openAction)
fileMenu.addAction(exitAction)


wid = QWidget(self)
self.setCentralWidget(wid)


controlLayout = QHBoxLayout()
controlLayout.setContentsMargins(0, 0, 0, 0)
controlLayout.addWidget(self.playButton)
controlLayout.addWidget(self.positionSlider)

layout = QVBoxLayout()
layout.addWidget(videoWidget)
layout.addLayout(controlLayout)
layout.addWidget(self.errorLabel)


wid.setLayout(layout)

self.mediaPlayer.setVideoOutput(videoWidget)
self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
self.mediaPlayer.positionChanged.connect(self.positionChanged)
self.mediaPlayer.durationChanged.connect(self.durationChanged)
self.mediaPlayer.error.connect(self.handleError)

def openFile(self):
fileName, _ = QFileDialog.getOpenFileName(self, "Open Movie",
QDir.homePath())

if fileName != '':
self.mediaPlayer.setMedia(
QMediaContent(QUrl.fromLocalFile(fileName)))
self.playButton.setEnabled(True)

def exitCall(self):
sys.exit(app.exec_())

def play(self):
if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
self.mediaPlayer.pause()
else:
self.mediaPlayer.play()

def mediaStateChanged(self, state):
if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
self.playButton.setIcon(
self.style().standardIcon(QStyle.SP_MediaPause))
else:
self.playButton.setIcon(
self.style().standardIcon(QStyle.SP_MediaPlay))

def positionChanged(self, position):
self.positionSlider.setValue(position)

def durationChanged(self, duration):
self.positionSlider.setRange(0, duration)

def setPosition(self, position):
self.mediaPlayer.setPosition(position)

def handleError(self):
self.playButton.setEnabled(False)
self.errorLabel.setText("Error: " + self.mediaPlayer.errorString())

if __name__ == '__main__':
app = QApplication(sys.argv)
player = VideoWindow()
player.resize(640, 480)
player.show()
sys.exit(app.exec_())

If you are new to Python PyQt, then I highly recommend this book.

Download PyQt Examples

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.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Product key for windows 10 pro
  • Install bluetooth driver for windows 10
  • Time windows ntp сервер
  • Подключение двух мониторов к одному компьютеру windows 10
  • Ошибка 0х80240017 при установке visual c windows