For calculation media files summary duration in a specific directory, we need ffprobe
and python
ffprobe
is an open source software for gathering information from multimedia streams and could be downloaded from: https://ffmpeg.org/ffprobe.html
For getting the media file duration we need to execute next command:
ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "my-media-file.mp4"
Next we need to get full list of files in a directory recursevly:
import os
paths = [os.path.join(dp, f) for dp, dn, filenames in os.walk(dir) for f in filenames]
Next we need loop through each files and execute command above with ffprobe
and get total duration in seconds:
import subprocess
summary_duration = 0.
for file in files:
cmd = 'ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "{}"'.format(file)
process = subprocess.run(cmd, shell=True, capture_output=True)
if (not process.stderr):
try:
seconds = float(process.stdout.decode("utf-8"))
except:
pass
In above code we’re ignoring any errors in case if files are not in valid format or inaccessible.
Finally, we can beautify the seconds in more readable format:
import datetime
str(datetime.timedelta(seconds=int(summary_duration)))
The final code could be downloaded from Git repository:
https://github.com/SUXUMI/calculate-media-files-summary-duration
usage sample:
$ calculate-media-files-summary-duration.py my-directory-path