I am new in Python and I am trying to get the duration (in seconds) of a file video by using ffprobe. Calling the following instruction
ffprobe -i video.mp4 -show_entries format=duration -v quiet -of csv="p=0"
on the CMD, I get the right result in seconds but if I call the same instruction in python by using:
import subprocess
duration = subprocess.call(['ffprobe', '-i', 'video.mp4', '-show_entries', 'format=duration', '-v', 'quiet', '-of', 'csv="p=0"'])
print duration
it returns 1. Is there a way to get the right result also through Python? Thank you in advance.
To get the duration with ffprobe, add the -show_entries flag and set its value to format=duration. This tells ffprobe to only return the duration. If you just want to get the numerical duration of the video in seconds with no wrappers, set the output format to noprint_wrappers=1:nokey=1 using the -of flag like this:
In this tutorial, we will learn how to get the duration of a video with FFmpeg using the ffprobe utility. To get the duration with ffprobe, add the -show_entries flag and set its value to format=duration.
The FFmpeg library, ffprobe, can rightly be called the Swiss Army Knife of video information extraction or video inspection. As the FFmpeg documentation succinctly puts it,
MoviePy is a python library, which can help us to operate video. In this tutorial, we will introduce how to get video duration with it. You can learn and do by following our tutorial. Install moviepy pip install moviepy Import libraries from moviepy.editor import VideoFileClip import datetime Create a VideoFileClip object with video file
The problem is with the double quote argument p=0
, format it using %
, also i changed subprocess.call
to subprocess.check_output
to store output of the command in a string :
import subprocess
duration = subprocess.check_output(['ffprobe', '-i', 'video.mp4', '-show_entries', 'format=duration', '-v', 'quiet', '-of', 'csv=%s' % ("p=0")])
print(duration)
Output:
8.824000
or you can otherwise do this:
import subprocess
result = subprocess.Popen(["ffprobe", "video.mp4"],stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
for x in result.stdout.readlines():
if "Duration" in x:
print(x[12:23])
break
from subprocess import check_output
file_name = "movie.mp4"
#For Windows
a = str(check_output('ffprobe -i "'+file_name+'" 2>&1 |findstr "Duration"',shell=True))
#For Linux
#a = str(check_output('ffprobe -i "'+file_name+'" 2>&1 |grep "Duration"',shell=True))
a = a.split(",")[0].split("Duration:")[1].strip()
h, m, s = a.split(':')
duration = int(h) * 3600 + int(m) * 60 + float(s)
print(duration)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With