问题
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