How do I find the length of media with gstreamer?
Asked Answered
M

4

14

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

Moorefield answered 13/3, 2010 at 23:44 Comment(0)
M
19

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

duration.py:

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

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

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

Examples:

$ python duration.py VIDEO_TS/VTS_03_1.VOB
0:20:10.528000
$ python duration.py ~/Movies/BigBuckBunny_640x360.m4v
0:09:56.461667
Moorefield answered 14/3, 2010 at 6:16 Comment(2)
It gives less than the total duration of the stream for me. It returns 880ms for a 83 seconds MKV video, for example. Maybe a problem with metadata? Other players play the file correctly and the MKV itself is produced by the same version of gstreamer.Hospitaler
@Moorefield Do you have the C# version of same?Deirdra
P
2

Why re-invent the wheel?
Use:
gst-discoverer-1.0 filename
or
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

Popovich answered 24/7, 2015 at 17:15 Comment(0)
S
1

See Section 6.5.

http://majorsilence.com/pygtk_audio_and_video_playback_gstreamer

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

Spellman answered 1/4, 2010 at 18:38 Comment(1)
Can you include the basic idea from this article in your post? Link only answers tend to rot over time. (this link is already 404)Kinghorn
I
1

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)
Inexpensive answered 14/3, 2023 at 3:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.