How do I get the duration of a video file?

On Linux, YouTube places temporary flash files in / tmp. Nautilus can display duration (minutes: seconds), but I haven't found a way to extract duration using python. 'The less your method depends, the better.

Thanks in advance.

+2


source to share


2 answers


One way to do this is with ffmpeg. ffmpeg must be installed with support for h.264 and h.263 codecs. Then comes the command to get the duration of the video, which can be called via python system(command)

.
ffmpeg -i flv_file 2>&1 | grep "Duration" | cut -d ' ' -f 4 | sed s/,//



+3


source


While this example may sound overwhelming, I did it as an exercise to get a better understanding of Python, and it makes working with the atomic parts of file duration easier.



#!/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)

      

+1


source







All Articles