Previously, I wrote about Counting Lines of Code in a given directory. Recently, I had a similar curiousity- “how long are all the video files in this folder?” This seemed to be a good fit for a Python script.
The main question, then, is how do we determine the length of a video file in Python? Once we have that problem solved, we can effectively use the same code as the CodeCount and “sum” all the lengths together in much the same way that the Code Count script sums all the line counts.
The most straightforward approach I discovered was using ffmpeg to retrieve video information, redirecting the output to a temp file, and then finding the listed Duration in that temp file. We then take that determined duration and parse it, and create a Python TimeDelta. We can use that TimeDelta, and sum all the TimeDelta’s of the files in question to determine the total run time of all the videos in the specified folders.
#! /usr/bin/env python
for root,subFolders,files in os.walk(folder):
for file in files:
tmpf = tempfile.NamedTemporaryFile()
fname = tmpf.name
sSystem = "D:\\programs\\ffmpeg\\static\\bin\\ffmpeg -i \"%s\" 2> %s" % (filepath, tmpf.name);
tmpf = open(fname)
lines = tmpf.readlines()
for l in lines:
l = l.strip()
getduration = re.search('Duration: (.*?),', l).group(0).split(':',1).strip(' ,')
timeparts = getduration.split(':') #hour,minute,second
if __name__ == '__main__':
searchfor = sys.argv
searchin = sys.argv
print("examining files matching " + searchfor + " in directory " + searchin)
for countthese in searchfolder(searchin,searchfor):
grablength = getVideoLength(countthese)
if grablength is not None:
totalcount = totalcount + getVideoLength(countthese)
print("total length:" + str(totalcount))
A bit of checking code to allow for the use of *.* to total all ffmpeg compatible video files rounds this out- the syntax is the same as the Code Counter- VidLength.py <FileMask> <directory< and it will display all the files it analyzes and then a total duration.