如何用Python获取视频的持续时间?

2024-04-28 07:13:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要用Python获取视频持续时间。我需要得到的视频格式是MP4,Flash视频,AVI,和MOV。。。我有一个共享的托管解决方案,所以我没有FFmpeg支持。


Tags: 视频解决方案ffmpegflashmp4持续时间mov视频格式
3条回答

为了让事情简单一点,下面的代码将输出设置为JSON

您可以使用probe(filename)来使用它,或者使用duration(filename)来获取持续时间:

json_info     = probe(filename)
secondes_dot_ = duration(filename) # float number of seconds

它在Ubuntu 14.04上工作,当然是在ffprobe上安装的。代码不是为了速度或美观而优化的,但它在我的机器上工作,希望它能有所帮助。

#
# Command line use of 'ffprobe':
#
# ffprobe -loglevel quiet -print_format json \
#         -show_format    -show_streams \
#         video-file-name.mp4
#
# man ffprobe # for more information about ffprobe
#

import subprocess32 as sp
import json


def probe(vid_file_path):
    ''' Give a json from ffprobe command line

    @vid_file_path : The absolute (full) path of the video file, string.
    '''
    if type(vid_file_path) != str:
        raise Exception('Gvie ffprobe a full file path of the video')
        return

    command = ["ffprobe",
            "-loglevel",  "quiet",
            "-print_format", "json",
             "-show_format",
             "-show_streams",
             vid_file_path
             ]

    pipe = sp.Popen(command, stdout=sp.PIPE, stderr=sp.STDOUT)
    out, err = pipe.communicate()
    return json.loads(out)


def duration(vid_file_path):
    ''' Video's duration in seconds, return a float number
    '''
    _json = probe(vid_file_path)

    if 'format' in _json:
        if 'duration' in _json['format']:
            return float(_json['format']['duration'])

    if 'streams' in _json:
        # commonly stream 0 is the video
        for s in _json['streams']:
            if 'duration' in s:
                return float(s['duration'])

    # if everything didn't happen,
    # we got here because no single 'return' in the above happen.
    raise Exception('I found no duration')
    #return None


if __name__ == "__main__":
    video_file_path = "/tmp/tt1.mp4"
    duration(video_file_path) # 10.008

如本文所述https://www.reddit.com/r/moviepy/comments/2bsnrq/is_it_possible_to_get_the_length_of_a_video/

你可以用电影模块

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

您可以为此使用外部命令^{}。具体来说,从FFmpeg Wiki运行this bash command

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)

相关问题 更多 >