Isaiah
Isaiah

Reputation: 4309

How to get duration of video flash file?

On Linux, YouTube places temporary flash files in /tmp. Nautilus can display the duration (Minutes:Seconds) of them, but I haven't found a way to extract the duration using python.' The fewer dependencies your method requires the better.

Thanks in advance.

Upvotes: 2

Views: 1734

Answers (2)

David Geller
David Geller

Reputation: 11

While this example may seem overly complicated, I did it as an exercise to better understand Python and it makes dealing with the atomic parts of the file's 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)

Upvotes: 1

bhups
bhups

Reputation: 14895

One way it can be done using ffmpeg. ffmpeg needs to be installed with h.264 and h.263 codec support. Then following is the command to retrieve the video duration, which can be called via python system(command).
ffmpeg -i flv_file 2>&1 | grep "Duration" | cut -d ' ' -f 4 | sed s/,//

Upvotes: 3

Related Questions