Skip to content

Instantly share code, notes, and snippets.

@zed
Last active August 29, 2015 14:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zed/de5ebbc08805a941a7f7 to your computer and use it in GitHub Desktop.
Save zed/de5ebbc08805a941a7f7 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""Play a media (audio/video) file using GStreamer.
To install Gstreamer and its Python bindings on Ubuntu, run:
$ sudo apt-get install python-gi python3-gi \
gstreamer1.0-tools \
gir1.2-gstreamer-1.0 \
gir1.2-gst-plugins-base-1.0 \
gstreamer1.0-plugins-good \
gstreamer1.0-plugins-ugly \
gstreamer1.0-plugins-bad \
gstreamer1.0-libav
"""
import os
import sys
try:
from urllib.parse import urljoin
from urllib.request import pathname2url
except ImportError: # Python 2
from urlparse import urljoin
from urllib import pathname2url
from gi.repository import GObject, Gst
Gst.init(None)
loop_playback = True
def path2url(path):
return urljoin('file:', pathname2url(os.path.abspath(path)))
def on_bus_msg(bus, msg):
# from https://github.com/vigsterkr/pi-wall/blob/master/src/player.py
if msg is None:
return
elif msg.type is Gst.MessageType.EOS:
if loop_playback:
player.seek_simple(Gst.Format.TIME,
Gst.SeekFlags.FLUSH | Gst.SeekFlags.KEY_UNIT,
0)
else:
sys.exit()
elif msg.type is Gst.MessageType.ERROR:
print("Got message of type ", msg.type)
print("Got message of src ", msg.src)
print("Got message of error ", msg.parse_error())
player.set_state(Gst.State.NULL)
sys.exit('error')
else:
pass # ignore other messages
media_uri = path2url(sys.argv[1]) # file:// url to play
print(media_uri)
player = Gst.ElementFactory.make('playbin', None)
player.set_property('uri', media_uri)
bus = player.get_bus()
watch_id = bus.connect("message", on_bus_msg) # listen for GStreamer's messages
bus.add_signal_watch()
player.set_state(Gst.State.PLAYING)
print('Press Ctrl-C to exit...')
try:
GObject.MainLoop().run()
except KeyboardInterrupt:
pass
finally:
player.set_state(Gst.State.NULL)
bus.remove_signal_watch()
bus.disconnect(watch_id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment