Skip to content

Instantly share code, notes, and snippets.

@MarcoForte

MarcoForte/fileDuration.py

Last active Aug 29, 2015
Embed
What would you like to do?
Get audio or video file duration with Powershell through Python on Windows
""" This module shows how to retrieve the duration of an audio or video file on Windows by getting the file details
with Powershell, tested on Powershell 4. """
import subprocess
myFileLocation = r"'C:\Users\Marco\Untitled.wma'" # or myFileLocation = 'C:\\Users\\yourname\\test.mp4'
def getFileDuration(fileLocation):
# Calls the Powershell script that gets the file duration
return subprocess.check_output([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe',
'(((New-Object -COMObject Shell.Application).Namespace((Split-Path {0})))).GetDetailsOf((((New-Object -COMObject Shell.Application).Namespace((Split-Path {0}))).ParseName((Split-Path {0} -Leaf))), 183);'.format(myFileLocation)]).decode("utf-8").splitlines()[0]
print(getFileDuration(myFileLocation))
"""
Converted to a one liner from here, http://superuser.com/questions/704575/get-song-duration-from-an-mp3-file-using-powershell
Though I had to change 27 to 183
Here's the multi-line version,
def getFileDuration(fileLocation):
# Calls the Powershell script that gets the file duration
return subprocess.check_output([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe',
'''$path = {0}
$shell = New-Object -COMObject Shell.Application
$folder = Split-Path $path
$file = Split-Path $path -Leaf
$shellfolder = $shell.Namespace($folder)
$shellfile = $shellfolder.ParseName($file)
$shellfolder.GetDetailsOf($shellfile, 183);'''.format(myFileLocation)]).decode("utf-8").splitlines()[0]
"""
""" If using 183 doesn't work a previous implementation I had got the file tip using -1 and extracted out the relevant info,
def getFileDuration(fileLocation):
# Calls the Powershell script that gets the file attributes, decodes to utf-8 for Python 3
output = subprocess.check_output([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe',
'echo (((New-Object -COMObject Shell.Application).Namespace((Split-Path {0})))).GetDetailsOf((((New-Object -COMObject Shell.Application).Namespace((Split-Path {0}))).ParseName((Split-Path {0} -Leaf))), -1);'.format(myFileLocation)]).decode("utf-8")
# Gets the lines which contains the length info, different index line depending on file
matched_lines = [line for line in output.split('\n') if "Length" in line]
# Takes the first line with length info and takes the relevant part of the line
return matched_lines[0][8:]
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.