Хотя этот пример может показаться слишком сложным, я сделал это как упражнение, чтобы лучше понять 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)