如何使用 PyQt5 播放视频的特定部分 [英] How to play a specific part of a video with PyQt5

查看:150
本文介绍了如何使用 PyQt5 播放视频的特定部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想播放视频的某个部分,例如,使用 PyQt5 播放从 30 秒到 33 秒的视频.我正在使用 Qmultimedia 小部件.

I would like to play a certain part of a video, for example, play a video from second 30 to second 33 using PyQt5. I am using the Qmultimedia widget.

这是我的播放器代码的样子.有没有办法在某个位置开始和结束?我一直在手动将视频剪辑到子剪辑中,然后只是播放这些子剪辑,但这非常耗时.谢谢!

This is how my player code looks. Is there a way to start and end at a certain position? I've been manually clipping the video into subclips and just playing those subclips instead but that's very time consuming. Thank you!

self.player = QtMultimedia.QMediaPlayer(None, QtMultimedia.QMediaPlayer.VideoSurface)
file = QtCore.QDir.current().filePath("path")
self.player.setMedia(QtMultimedia.QMediaContent(QtCore.QUrl.fromLocalFile(file)))
self.player.setVideoOutput(self.ui.videoWidget)
self.player.play()

推荐答案

您可以使用 setPosition() 方法设置以毫秒为单位的位置,并通过 positionChanged 信号您可以监控经过的时间以停止播放

You can set the position in ms with the setPosition() method, and through the positionChanged signal you can monitor the elapsed time to stop the playback

import os
from PyQt5 import QtCore, QtWidgets, QtMultimedia, QtMultimediaWidgets


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        video_widget = QtMultimediaWidgets.QVideoWidget()
        self.setCentralWidget(video_widget)
        self.player = QtMultimedia.QMediaPlayer(self, QtMultimedia.QMediaPlayer.VideoSurface)
        self.player.setVideoOutput(video_widget)
        # period of time that the change of position is notified
        self.player.setNotifyInterval(1)
        self.player.positionChanged.connect(self.on_positionChanged)

    def setInterval(self, path, start, end):
        """
            path: path of video
            start: time in ms from where the playback starts
            end: time in ms where playback ends
        """
        self.player.stop()
        self.player.setMedia(QtMultimedia.QMediaContent(QtCore.QUrl.fromLocalFile(path)))
        self.player.setPosition(start)
        self._end = end
        self.player.play()

    @QtCore.pyqtSlot('qint64')
    def on_positionChanged(self, position):
        if self.player.state() == QtMultimedia.QMediaPlayer.PlayingState:
            if position > self._end:
                self.player.stop()


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    file = os.path.join(os.path.dirname(__file__), "test.mp4")
    w.setInterval(file, 30*1000, 33*1000)
    w.show()
    sys.exit(app.exec_())

这篇关于如何使用 PyQt5 播放视频的特定部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆