实现流媒体播放器uuuuuuuuuuu
立即下载
资源介绍:
实现流媒体播放器uuuuuuuuuuu
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
import cv2
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QImage, QPixmap
from play import Ui_MainWindow # 假设你的 UI 文件名为 play.py,生成的类为 Ui_MainWindow
class VideoPlayer(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
# 设置界面
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
# 设置按钮连接
self.ui.select.clicked.connect(self.open_video_folder)
self.ui.pushButton_2.clicked.connect(self.toggle_play_pause)
self.playing = False
# 初始化视频相关变量
self.video_path = ""
self.video_capture = None
self.timer = QTimer(self)
self.timer.timeout.connect(self.update_frame)
self.current_frame = None
#进度条
self.ui.horizontalSlider.sliderMoved.connect(self.set_video_position)
def open_video_folder(self):
self.video_path, _ = QtWidgets.QFileDialog.getOpenFileName(self, "选择视频文件", "", "视频文件 (*.mp4 *.avi)")
if self.video_path:
self.start_video()
def start_video(self):
self.video_capture = cv2.VideoCapture(self.video_path)
total_frames = int(self.video_capture.get(cv2.CAP_PROP_FRAME_COUNT))
self.ui.horizontalSlider.setMinimum(0)
self.ui.horizontalSlider.setMaximum(total_frames - 1)
self.timer.start(30) # 设置更新频率,单位毫秒
self.playing = True # 开始播放视频时,设置 playing 为 True
def update_frame(self):
if self.playing:
ret, frame = self.video_capture.read()
if ret:
self.current_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
h, w, ch = self.current_frame.shape
bytes_per_line = ch * w
qt_img = QImage(self.current_frame.data, w, h, bytes_per_line, QImage.Format_RGB888)
pixmap = QPixmap.fromImage(qt_img)
self.ui.player.setPixmap(pixmap.scaled(self.ui.player.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
else:
self.timer.stop()
self.video_capture.release()
print("视频播放完毕!")
def toggle_play_pause(self):
if self.playing:
# 如果正在播放,则暂停
print("Pausing playback")
self.playing = False # 设置播放状态为 False,不再更新帧
else:
# 如果已经暂停,则继续播放
print("Resuming playback")
self.playing = True # 设置播放状态为 True,继续更新帧
def set_video_position(self, position):
self.video_capture.set(cv2.CAP_PROP_POS_FRAMES, position)
ret, frame = self.video_capture.read()
print(ret)
if ret:
self.current_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
h, w, ch = self.current_frame.shape
bytes_per_line = ch * w
qt_img = QImage(self.current_frame.data, w, h, bytes_per_line, QImage.Format_RGB888)
pixmap = QPixmap.fromImage(qt_img)
self.ui.player.setPixmap(pixmap.scaled(self.ui.player.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
def main():
app = QtWidgets.QApplication(sys.argv)
window = VideoPlayer()
window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()