How to get online video duration without downloading full video?
To get the duration and resolution of a video, I have this function:
def getvideosize(url, verbose=False):
try:
if url.startswith('http:') or url.startswith('https:'):
ffprobe_command = ['ffprobe', '-icy', '0', '-loglevel', 'repeat+warning' if verbose else 'repeat+error', '-print_format', 'json', '-select_streams', 'v', '-show_streams', '-timeout', '60000000', '-user-agent', BILIGRAB_UA, url]
else:
ffprobe_command = ['ffprobe', '-loglevel', 'repeat+warning' if verbose else 'repeat+error', '-print_format', 'json', '-select_streams', 'v', '-show_streams', url]
logcommand(ffprobe_command)
ffprobe_process = subprocess.Popen(ffprobe_command, stdout=subprocess.PIPE)
try:
ffprobe_output = json.loads(ffprobe_process.communicate()[0].decode('utf-8', 'replace'))
except KeyboardInterrupt:
logging.warning('Cancelling getting video size, press Ctrl-C again to terminate.')
ffprobe_process.terminate()
return 0, 0
width, height, widthxheight, duration = 0, 0, 0, 0
for stream in dict.get(ffprobe_output, 'streams') or []:
if dict.get(stream, 'duration') > duration:
duration = dict.get(stream, 'duration')
if dict.get(stream, 'width')*dict.get(stream, 'height') > widthxheight:
width, height = dict.get(stream, 'width'), dict.get(stream, 'height')
if duration == 0:
duration = 1800
return [[int(width), int(height)], int(float(duration))+1]
except Exception as e:
logorraise(e)
return [[0, 0], 0]
But some online videos appear without a tag duration
. Is there anything we can do to get its duration?
source to share
If you have a direct link to a video like http://www.dl.com/xxx.mp4 you can directly use ffprobe
to get the duration of that video with:
ffprobe -i some_video_direct_link -show_entries format=duration -v quiet -of csv="p=0"
source to share
I know this question is old, but there is a better way to do it.
By combining einverne's answer with some actual Python (in this case Python 3.5), we can create a short function that returns the number of seconds (duration) in the video.
import subprocess
def get_duration(file):
"""Get the duration of a video using ffprobe."""
cmd = 'ffprobe -i {} -show_entries format=duration -v quiet -of csv="p=0"'.format(file)
output = subprocess.check_output(
cmd,
shell=True,
stderr=subprocess.STDOUT
)
output = float(output)
return round(output)
And to call this function:
video_length_in_seconds = get_duration('/path/to/your/file') # mp4, avi, etc
This will give you the total number of seconds, rounded up to the nearest full second. So if your video is 30.6 seconds this will return 31
.
The FFMpeg team ffprobe -i video_file_here -show_entries format=duration -v quiet -of csv="p=0"
will get your video duration for you and doesn't have to download all of the videos.
source to share