PyQt5开发设计播放器
时间: 2023-11-13 09:05:36 浏览: 74
PyQt5是一个Python GUI编程工具包,支持多种操作系统,包括Windows、Linux、MacOS等。使用PyQt5可以轻松实现各种GUI界面的开发,包括播放器。
下面是一个简单的播放器界面设计示例:
```python
from PyQt5.QtCore import Qt, QUrl
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QVBoxLayout, QLabel, QSlider, QPushButton, QFileDialog, QStyle, QSizePolicy
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)
# 创建界面
self.createUI()
# 播放器信号连接
self.mediaPlayer.setVideoOutput(self.videoWidget)
self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
self.mediaPlayer.positionChanged.connect(self.positionChanged)
self.mediaPlayer.durationChanged.connect(self.durationChanged)
def createUI(self):
# 创建视频显示窗口
self.videoWidget = QLabel(self)
self.videoWidget.setStyleSheet("background-color:black;")
self.videoWidget.setMinimumSize(640, 480)
# 创建播放按钮
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.openButton = QPushButton("打开文件")
self.openButton.clicked.connect(self.openFile)
# 创建水平布局
hboxLayout = QHBoxLayout()
hboxLayout.setContentsMargins(0, 0, 0, 0)
hboxLayout.addWidget(self.playButton)
hboxLayout.addWidget(self.positionSlider)
# 创建垂直布局
vboxLayout = QVBoxLayout()
vboxLayout.addWidget(self.videoWidget)
vboxLayout.addLayout(hboxLayout)
vboxLayout.addWidget(self.openButton)
self.setLayout(vboxLayout)
# 界面设置
self.setWindowTitle("播放器")
self.setWindowIcon(QIcon("icon.png"))
def openFile(self):
fileName, _ = QFileDialog.getOpenFileName(self, "选择视频文件", ".", "视频文件 (*.mp4 *.avi *.mkv)")
if fileName != "":
self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile(fileName)))
self.playButton.setEnabled(True)
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)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
```
这个播放器界面包括一个视频显示窗口、一个播放按钮、一个进度条和一个打开按钮。用户可以通过打开按钮选择视频文件进行播放,播放时可以通过播放按钮控制播放和暂停,进度条可以显示当前播放进度并可以通过拖动改变播放位置。
阅读全文