如何使用PyQt5播放视频的特定部分

时间:2018-11-05 05:30:05

标签: python python-3.x video pyqt

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

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

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()

1 个答案:

答案 0 :(得分:2)

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

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_())