获取python中特定目录中视频的总长度 [英] Get total length of videos in a particular directory in python

查看:27
本文介绍了获取python中特定目录中视频的总长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 coursera.org 下载了一堆视频,并将它们存储在一个特定文件夹中.特定文件夹中有许多单独的视频(Coursera 将一个讲座分成多个短视频).我想要一个 python 脚本,它给出特定目录中所有视频的组合长度.视频文件为 .mp4 格式.

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.

推荐答案

首先,安装ffprobe 命令(它是 FFmpeg 的一部分)与

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

sudo apt install ffmpeg

然后使用 subprocess.run()运行这个 bash 命令:

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

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

(我从 http://trac.ffmpeg.org/wiki/FFprobeTips# 获得)Formatcontainerduration),像这样:

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()))

此代码需要 Python 3.7+,因为那时将 text=capture_output= 添加到 subprocess.run>.如果您使用的是较旧的 Python 版本,请查看此答案的编辑历史记录.

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.

这篇关于获取python中特定目录中视频的总长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆