[파이썬] PyQt 오디오 및 비디오 재생 (`QMediaPlayer`)

PyQt is a powerful GUI toolkit for Python that provides various widgets and functionalities to create desktop applications. One of the useful features provided by PyQt is the ability to play audio and video files using the QMediaPlayer class.

In this blog post, we will explore how to use QMediaPlayer in PyQt to play audio and video files in Python.

Installation

To get started, you need to have PyQt installed on your system. You can install it using pip:

pip install pyqt5

Playing Audio Files

Let’s start by playing an audio file using QMediaPlayer. First, we need to import the necessary modules:

from PyQt5.QtCore import QUrl
from PyQt5.QtMultimedia import QMediaPlayer
from PyQt5.QtWidgets import QApplication

Next, we create an instance of QApplication:

app = QApplication([])

Then, we create an instance of QMediaPlayer and set the audio file to be played:

player = QMediaPlayer()
player.setMedia(QUrl.fromLocalFile("audio.mp3"))

Finally, we play the audio file:

player.play()

When you run the code, it will create a minimal application window and play the audio file specified. You can also pause, stop, and adjust the volume of the audio using methods provided by QMediaPlayer.

Playing Video Files

Playing video files is similar to playing audio files. However, we need to use a QVideoWidget to display the video. Here’s how you can play a video file:

from PyQt5.QtMultimediaWidgets import QVideoWidget
from PyQt5.QtWidgets import QMainWindow, QVBoxLayout, QWidget

app = QApplication([])

window = QMainWindow()
video_widget = QVideoWidget()

player = QMediaPlayer()
player.setVideoOutput(video_widget)
player.setMedia(QUrl.fromLocalFile("video.mp4"))

layout = QVBoxLayout()
layout.addWidget(video_widget)

widget = QWidget()
widget.setLayout(layout)

window.setCentralWidget(widget)
window.show()

player.play()

The code above creates a window with a QVideoWidget and sets it as the video output for QMediaPlayer. You can replace “video.mp4” with the path to your desired video file.

Conclusion

In this blog post, we learned how to use QMediaPlayer in PyQt to play audio and video files. We saw how to play audio files and control playback, as well as how to display video using QVideoWidget.

PyQt provides a lot more functionality for working with media files, such as playing streams from the internet and handling playback events. Make sure to check out the official PyQt documentation for more information and examples.

Happy coding!