使用pyside6实现视频播放器
时间: 2024-12-27 22:25:00 浏览: 7
### 使用 PySide6 创建视频播放器
为了创建基于 PySide6 的视频播放器,可以利用 `QMediaPlayer` 和 `QVideoWidget` 组件来实现基本功能[^1]。
下面是一个简单的例子展示如何构建一个基础的视频播放器:
```python
import sys
from PySide6.QtWidgets import QApplication, QMainWindow, QFileDialog, QPushButton, QVBoxLayout, QWidget
from PySide6.QtMultimedia import QMediaPlayer
from PySide6.QtMultimediaWidgets import QVideoWidget
class VideoPlayer(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('PySide6 Video Player')
# Create media player object
self.media_player = QMediaPlayer()
# Create video widget as the display area
video_widget = QVideoWidget()
self.setCentralWidget(video_widget)
# Connect media player and video widget
self.media_player.setVideoOutput(video_widget)
# Add buttons layout
open_button = QPushButton("Open File")
play_button = QPushButton("Play/Pause")
open_button.clicked.connect(self.open_file)
play_button.clicked.connect(self.play_pause)
control_layout = QVBoxLayout()
control_layout.addWidget(open_button)
control_layout.addWidget(play_button)
container = QWidget()
container.setLayout(control_layout)
self.setMenuWidget(container)
def open_file(self):
file_name, _ = QFileDialog.getOpenFileName(self, "Open Movie", "", "Movie Files (*.mp4 *.avi)")
if file_name != '':
self.media_player.setSource(file_name)
def play_pause(self):
if self.media_player.isPlaying():
self.media_player.pause()
else:
self.media_player.play()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = VideoPlayer()
window.resize(800, 600)
window.show()
sys.exit(app.exec())
```
这段代码定义了一个名为 `VideoPlayer` 的类继承自 `QMainWindow`,实现了打开文件对话框选择媒体文件以及控制播放/暂停的功能。通过设置布局管理器和信号槽机制连接各个控件之间的交互逻辑[^2]。
阅读全文