如何获取Flash视频文件的时长?

2 投票
2 回答
1729 浏览
提问于 2025-04-15 15:19

在Linux系统上,YouTube会把临时的闪存文件放在/tmp这个文件夹里。Nautilus(一个文件管理器)可以显示这些文件的时长(分钟:秒),但是我还没找到用Python提取这些时长的方法。

如果你的方法依赖的东西越少越好。

2 个回答

1

虽然这个例子看起来有点复杂,但我这样做是为了更好地理解Python,并且这样处理文件的时长的基本部分会更简单。

#!/usr/bin/env python

"""
    duration
    =========
    Display the duration of a video file. Utilizes ffmpeg to retrieve that information

    Usage:
    #duration file
    bash-3.2$ ./dimensions.py src_video_file

"""

import subprocess
import sys
import re

FFMPEG = '/usr/local/bin/ffmpeg'

# -------------------------------------------------------
# Get the duration from our input string and return a
# dictionary of hours, minutes, seconds
# -------------------------------------------------------
def searchForDuration (ffmpeg_output):

    pattern = re.compile(r'Duration: ([\w.-]+):([\w.-]+):([\w.-]+),')   
    match = pattern.search(ffmpeg_output)   

    if match:
        hours = match.group(1)
        minutes = match.group(2)
        seconds = match.group(3)
    else:
        hours = minutes = seconds = 0

    # return a dictionary containing our duration values
    return {'hours':hours, 'minutes':minutes, 'seconds':seconds}

# -----------------------------------------------------------
# Get the dimensions from the specified file using ffmpeg
# -----------------------------------------------------------
def getFFMPEGInfo (src_file):

    p = subprocess.Popen(['ffmpeg', '-i', src_file],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    stdout, stderr = p.communicate()
    return stderr

# -----------------------------------------------------------
# Get the duration by pulling out the FFMPEG info and then
# searching for the line that contains our duration values
# -----------------------------------------------------------
def getVideoDuration (src_file):

    ffmpeg_output = getFFMPEGInfo (src_file)
    return searchForDuration (ffmpeg_output)

if __name__ == "__main__":
    try:  
        if 2==len(sys.argv):
            file_name = sys.argv[1]
            d = getVideoDuration (file_name)
            print d['hours'] + ':' + d['minutes'] + ':' + d['seconds']

        else:
            print 'Error: wrong number of arguments'

    except Exception, e:
        print e
        raise SystemExit(1)
3

有一种方法可以使用ffmpeg来实现。首先,你需要安装ffmpeg,并确保它支持h.264和h.263这两种编码格式。接下来,下面这个命令可以用来获取视频的时长,你可以通过Python中的system(command)来调用它。
ffmpeg -i flv_file 2>&1 | grep "Duration" | cut -d ' ' -f 4 | sed s/,//

撰写回答