How to Get the Duration of a Video in Python

How to get the duration of a video in Python?

You can use the external command ffprobe for this. Specifically, run this bash command from the FFmpeg Wiki:

import subprocess

def get_length(filename):
result = subprocess.run(["ffprobe", "-v", "error", "-show_entries",
"format=duration", "-of",
"default=noprint_wrappers=1:nokey=1", filename],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
return float(result.stdout)

How to get the duration of video using OpenCV

OpenCV is not designed to explore video metadata, so VideoCapture doesn't have API to retrieve it directly.

You can instead "measure" the length of the stream: seek to the end, then get the timestamp:

>>> import cv2 as cv
>>> v = cv.VideoCapture('sample.avi')
>>> v.set(cv.CAP_PROP_POS_AVI_RATIO, 1)
True
>>> v.get(cv.CAP_PROP_POS_MSEC)
213400.0

Checking shows that this sets the point after the last frame (not before it), so the timestamp is indeed the exact total length of the stream:

>>> v.get(cv.CAP_PROP_POS_FRAMES)
5335.0
>>>> v.get(cv.CAP_PROP_FRAME_COUNT)
5335.0

>>> v.set(cv.CAP_PROP_POS_AVI_RATIO, 0)
>>> v.get(cv.CAP_PROP_POS_FRAMES)
0.0 # the 1st frame is frame 0, not 1, so "5335" means after the last frame

How to get the total time and current time of a video on a web page using python-selenium

because you might be using a wrong selector.
Example in the youtube videos, you can easily find the youtube total video length by using the xpath //span[@class='ytp-time-duration']

How to get video duration by youtube-dl in python?

just simple

dictMeta['duration']


Related Topics



Leave a reply



Submit