pyside2 制作视频播放器
时间: 2023-10-06 10:08:06 浏览: 101
制作视频播放器
要使用 PySide2 制作视频播放器,你可以使用 QtMultimedia 模块。以下是一个简单的示例代码:
```python
import sys
from PySide2.QtCore import Qt, QUrl
from PySide2.QtGui import QPalette, QColor
from PySide2.QtMultimedia import QMediaPlayer, QMediaContent
from PySide2.QtWidgets import QApplication, QMainWindow, QWidget, QHBoxLayout, QVBoxLayout, QLabel, QSlider, QPushButton
class VideoPlayer(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Video Player")
self.setGeometry(100, 100, 800, 600)
# 创建视频播放器和媒体内容
self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)
videoWidget = QWidget(self)
self.setCentralWidget(videoWidget)
videoLayout = QVBoxLayout(videoWidget)
videoLayout.setContentsMargins(0, 0, 0, 0)
videoLayout.addWidget(self.mediaPlayer.videoOutput())
self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
# 创建控制面板
controlWidget = QWidget(self)
controlLayout = QHBoxLayout(controlWidget)
controlLayout.setContentsMargins(0, 0, 0, 0)
self.playButton = QPushButton("播放", controlWidget)
self.playButton.setEnabled(False)
self.playButton.clicked.connect(self.playClicked)
self.positionSlider = QSlider(Qt.Horizontal, controlWidget)
self.positionSlider.setRange(0, 0)
self.positionSlider.sliderMoved.connect(self.setPosition)
self.positionLabel = QLabel(controlWidget)
self.positionLabel.setAlignment(Qt.AlignRight)
self.positionLabel.setMinimumWidth(100)
controlLayout.addWidget(self.playButton)
controlLayout.addWidget(self.positionSlider)
controlLayout.addWidget(self.positionLabel)
# 将控制面板添加到主窗口
mainLayout = QVBoxLayout()
mainLayout.addWidget(videoWidget)
mainLayout.addWidget(controlWidget)
self.statusBar().hide()
self.centralWidget().setLayout(mainLayout)
def openFile(self):
fileName, _ = QFileDialog.getOpenFileName(self, "选择视频文件", "", "视频文件 (*.mp4 *.avi)")
if fileName != '':
self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile(fileName)))
self.playButton.setEnabled(True)
def playClicked(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.setText("暂停")
else:
self.playButton.setText("播放")
def setPosition(self, position):
self.mediaPlayer.setPosition(position)
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setApplicationName("Video Player")
app.setPalette(QPalette(QColor(0, 0, 0)))
player = VideoPlayer()
player.show()
sys.exit(app.exec_())
```
这个示例代码创建了一个简单的视频播放器界面,包括一个视频播放器和一个控制面板。你可以通过打开按钮选择要播放的视频文件,并在控制面板上控制视频的播放、暂停和位置。你可以根据自己的需求进行修改和扩展。
阅读全文