Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get total length of videos in a particular directory in python

I have downloaded a bunch of videos from coursera.org and have them stored in one particular folder. There are many individual videos in a particular folder (Coursera breaks a lecture into multiple short videos). I would like to have a python script which gives the combined length of all the videos in a particular directory. The video files are .mp4 format.

like image 221
hardikudeshi Avatar asked Feb 23 '13 13:02

hardikudeshi


1 Answers

First, install the ffprobe command (it's part of FFmpeg) with

sudo apt install ffmpeg

then use subprocess.run() to run this bash command:

ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 -- <filename>

(which I got from http://trac.ffmpeg.org/wiki/FFprobeTips#Formatcontainerduration), like this:

from pathlib import Path
import subprocess

def video_length_seconds(filename):
    result = subprocess.run(
        [
            "ffprobe",
            "-v",
            "error",
            "-show_entries",
            "format=duration",
            "-of",
            "default=noprint_wrappers=1:nokey=1",
            "--",
            filename,
        ],
        capture_output=True,
        text=True,
    )
    try:
        return float(result.stdout)
    except ValueError:
        raise ValueError(result.stderr.rstrip("\n"))

# a single video
video_length_seconds('your_video.webm')

# all mp4 files in the current directory (seconds)
print(sum(video_length_seconds(f) for f in Path(".").glob("*.mp4")))

# all mp4 files in the current directory and all its subdirectories
# `rglob` instead of `glob`
print(sum(video_length_seconds(f) for f in Path(".").rglob("*.mp4")))

# all files in the current directory
print(sum(video_length_seconds(f) for f in Path(".").iterdir() if f.is_file()))

This code requires Python 3.7+ because that's when text= and capture_output= were added to subprocess.run. If you're using an older Python version, check the edit history of this answer.

like image 77
Boris Avatar answered Oct 03 '22 15:10

Boris