How to play a specific part of a video with PyQt5

和自甴很熟 提交于 2021-01-27 20:32:50

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/53148815/how-to-play-a-specific-part-of-a-video-with-pyqt5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!