1. 开发环境

1. 系统环境

Ubuntu22.04,python 3.10.12,

2.安装依赖

pip install python-vlc==3.0.21203
pip install PyQt5==5.15.11

3.代码实现

# encoding: utf-8
# @Time    : 2024/12/27 下午5:26
# @File    : pyqt5-vlc.py
import os

import vlc
from PyQt5.QtCore import Qt
from PyQt5.QtMultimediaWidgets import QVideoWidget
from PyQt5.QtWidgets import QMainWindow, QDockWidget, QHBoxLayout, QPushButton, QStyle, QWidget, QApplication


class VideoPlayer(QMainWindow):

    def __init__(self):
        super().__init__()

        self.setGeometry(100, 100, 800, 600)

        # 使用 QVideoWidget 作为视频显示部件
        self.video_widget = QVideoWidget()
        self.setCentralWidget(self.video_widget)

        # 创建 UI
        self.create_ui()

        self.instance = vlc.Instance()
        self.player = self.instance.media_player_new()

    def create_dock_widget(self, widget):
        dock = QDockWidget()
        dock.setWidget(widget)
        dock.setFeatures(QDockWidget.NoDockWidgetFeatures)
        return dock

    def create_ui(self):
        control_layout = QHBoxLayout()

        # 播放按钮
        self.play_button = QPushButton()
        self.play_button.setEnabled(False)
        self.play_button.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))

        self.play_button.clicked.connect(self.toggle_play_pause)

        control_layout.addWidget(self.play_button)

        control_widget = QWidget()
        control_widget.setLayout(control_layout)

        self.dockWidget = self.create_dock_widget(control_widget)
        self.addDockWidget(Qt.BottomDockWidgetArea, self.dockWidget)

    def open_vide(self, path):
        if os.path.isfile(path) or path.startswith(('http://', 'https://')):
            self.video_path = path

            self.media = self.instance.media_new(self.video_path)
            self.player.set_media(self.media)
            self.media.parse()

            # 将 VLC 播放器的输出窗口设置为 QVideoWidget
            self.player.set_xwindow(int(self.video_widget.winId()))
            self.play_button.setEnabled(True)

    def toggle_play_pause(self):
        if self.player.is_playing():
            self.player.pause()
            self.play_button.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        else:
            self.player.play()
            self.play_button.setIcon(self.style().standardIcon(QStyle.SP_MediaPause))


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    player = VideoPlayer()
    video_path = 'https://github.com/facefusion/facefusion-assets/releases/download/examples-3.0.0/target-240p.mp4'
    player.open_vide(video_path)
    player.show()
    sys.exit(app.exec_())

以上代码,仅实现了pyqt5中使用vlc播放器的播放功能。VLC播放器要比QT5中自带的多媒体播放器更好用!

参考: python-vlc