How to get the duration of a video in Python? How to get the duration of a video in Python? python 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 subprocessdef 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)


As reported here https://www.reddit.com/r/moviepy/comments/2bsnrq/is_it_possible_to_get_the_length_of_a_video/

you could use the moviepy module

from moviepy.editor import VideoFileClipclip = VideoFileClip("my_video.mp4")print( clip.duration )


(year 2020 answer)

Solutions:

  1. opencv 0.0065 sec ✔
  2. ffprobe 0.0998 sec
  3. moviepy 2.8239 sec

OpenCV method:

def with_opencv(filename):    import cv2    video = cv2.VideoCapture(filename)    duration = video.get(cv2.CAP_PROP_POS_MSEC)    frame_count = video.get(cv2.CAP_PROP_FRAME_COUNT)    return duration, frame_count

Usage: print(with_opencv('my_video.webm'))


Other:

ffprobe method:

def with_ffprobe(filename):    import subprocess, json    result = subprocess.check_output(            f'ffprobe -v quiet -show_streams -select_streams v:0 -of json "{filename}"',            shell=True).decode()    fields = json.loads(result)['streams'][0]    duration = fields['tags']['DURATION']    fps      = eval(fields['r_frame_rate'])    return duration, fps

moviepy method:

def with_moviepy(filename):    from moviepy.editor import VideoFileClip    clip = VideoFileClip(filename)    duration       = clip.duration    fps            = clip.fps    width, height  = clip.size    return duration, fps, (width, height)