Skip to content

Instantly share code, notes, and snippets.

@jaivikram
Last active April 18, 2020 13:02
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save jaivikram/4690569 to your computer and use it in GitHub Desktop.
Save jaivikram/4690569 to your computer and use it in GitHub Desktop.
Python gist to obtain video details like duration, resolution, bitrate, video codec and audio codec, frequency using 'ffmpeg'
#! /usr/bin/env python
import os
import sys
import re
import tempfile
def getVideoDetails(filepath):
tmpf = tempfile.NamedTemporaryFile()
os.system("ffmpeg -i \"%s\" 2> %s" % (filepath, tmpf.name))
lines = tmpf.readlines()
tmpf.close()
metadata = {}
for l in lines:
l = l.strip()
if l.startswith('Duration'):
metadata['duration'] = re.search('Duration: (.*?),', l).group(0).split(':',1)[1].strip(' ,')
metadata['bitrate'] = re.search("bitrate: (\d+ kb/s)", l).group(0).split(':')[1].strip()
if l.startswith('Stream #0:0'):
metadata['video'] = {}
metadata['video']['codec'], metadata['video']['profile'] = \
[e.strip(' ,()') for e in re.search('Video: (.*? \(.*?\)),? ', l).group(0).split(':')[1].split('(')]
metadata['video']['resolution'] = re.search('([1-9]\d+x\d+)', l).group(1)
metadata['video']['bitrate'] = re.search('(\d+ kb/s)', l).group(1)
metadata['video']['fps'] = re.search('(\d+ fps)', l).group(1)
if l.startswith('Stream #0:1'):
metadata['audio'] = {}
metadata['audio']['codec'] = re.search('Audio: (.*?) ', l).group(1)
metadata['audio']['frequency'] = re.search(', (.*? Hz),', l).group(1)
metadata['audio']['bitrate'] = re.search(', (\d+ kb/s)', l).group(1)
return metadata
if __name__ == '__main__':
if len(sys.argv) != 2:
print("Usage: ./getVideoDetails.py <filepath(absolute or relative)>")
sys.exit("Syntax Error")
print( getVideoDetails(sys.argv[1]) )
@jtraub
Copy link

jtraub commented Oct 27, 2015

It is easier to use ffprobe with -print_format json option.

@oldo
Copy link

oldo commented Dec 18, 2015

A quick little gist that uses the method suggested by @jtraub but only returns the file's resolution can be found here: https://gist.github.com/oldo/dc7ee7f28851922cca09
It could easily be modified to retrieve any other metadata too.

@mpathy
Copy link

mpathy commented Mar 26, 2016

there are already libs for that.. hachoir, enzyme and so on..
but nice for including in a small all in one script.. :)

@dankalytovskyy
Copy link

Few video files i tried all i get is {}
Is it supposed to be specific video formats?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment