2009-10-23 88 views
2

在Linux上,YouTube會在/ tmp中放置臨時Flash文件。鸚鵡螺可以顯示它們的持續時間(分鐘:秒),但我還沒有找到一種方法來使用python提取持續時間。' 您的方法需要的依賴性越少越好。如何獲得視頻閃存文件的持續時間?

在此先感謝。

回答

3

可以使用ffmpeg完成的一種方法。 ffmpeg需要安裝h.264和h.263編解碼器支持。接下來是檢索視頻持續時間的命令,可以通過python system(command)調用。
ffmpeg -i flv_file 2>&1 | grep "Duration" | cut -d ' ' -f 4 | sed s/,//

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) 
相關問題