How do I find the length of media with gstreamer?


How do I find the playback time of media with gstreamer?

Asked By: joeforker



Here’s a simple Python script to get the duration of anything gstreamer can decode. Note that all times in gstreamer are in nanoseconds.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division

import sys
import gobject
import pygst
import gst
d = gst.parse_launch("filesrc name=source ! decodebin2 ! fakesink")
source = d.get_by_name("source")
source.set_property("location", sys.argv[1])
format = gst.Format(gst.FORMAT_TIME)
duration = d.query_duration(format)[0]

import datetime
delta = datetime.timedelta(seconds=(duration / gst.SECOND))
print delta


$ python VIDEO_TS/VTS_03_1.VOB
$ python ~/Movies/BigBuckBunny_640x360.m4v
Answered By: joeforker

See Section 6.5.

It avoids need to create a pipeline and run it manually.

Answered By: Hardy

Why re-invent the wheel?
gst-discoverer-1.0 filename
gst-discoverer-0.10 filename

Depending on the file type you may want to add ” | grep Duration” to avoid the tags which can be lengthy.
For the ridding of extraneous tags for video,flac and mp3 files this should do the trick by using grep to exclude them.
gst-discoverer-1.0 filename | grep -v Tags | grep -v ID3v2 | grep -v image | grep -v attachment

Answered By: Rolf of Saxony

Adding on to the answer for gstreamer greater then 1.16.
Using GstPbutils and Discoverer we can query duration and other attributes as well. Full API here

import gi
gi.require_version("GstPbutils", "1.0")
from gi.repository import GstPbutils

def get_file_duration(file: Path) -> timedelta:
    discoverer = GstPbutils.Discoverer()
    asset_info = discoverer.discover_uri(str(file_path.as_uri()))
    duration_in_microseconds = int(asset_info.get_duration() / 1000)
    return timedelta(microseconds=duration_in_microseconds)
Answered By: Niru
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.