python: update python examples to modern python, Gst, and Glib versions
[experiments/gstreamer.git] / python / gst-looping-video-1.py
1 #!/usr/bin/env python3
2 #
3 # A simple looping player.
4 # Version 1, based on EOS handling.
5 #
6 # Get a test sample with:
7 # youtube-dl -t http://www.youtube.com/watch?v=yWa-YXiSk2Y
8
9 import sys
10
11 import gi
12 gi.require_version('Gst', '1.0')
13 from gi.repository import Gst
14 Gst.init(None)
15
16 from gi.repository import GLib
17
18
19 class Player:
20     def __init__(self, uri):
21         self._player = Gst.ElementFactory.make("playbin", "player")
22         self._player.set_property("uri", uri)
23
24         bus = self._player.get_bus()
25         bus.add_signal_watch()
26         bus.connect('message::eos', self.on_eos)
27         bus.connect('message::error', self.on_error)
28
29     def run(self):
30         self._player.set_state(Gst.State.PLAYING)
31         self.loop = GLib.MainLoop()
32         self.loop.run()
33
34     def quit(self):
35         self._player.set_state(Gst.State.NULL)
36         self.loop.quit()
37
38     def on_eos(self, bus, msg):
39         sys.stderr.write(".")
40         self._player.seek_simple(Gst.Format.TIME, Gst.SeekFlags.FLUSH, 0)
41
42     def on_error(self, bus, msg):
43         (err, debug) = msg.parse_error()
44         print("Error: %s" % err, debug)
45         self.quit()
46
47
48 def main(args):
49     def usage():
50         sys.stdout.write("usage: %s <filename>\n" % args[0])
51
52     if len(args) != 2:
53         usage()
54         sys.exit(1)
55
56     uri = Gst.filename_to_uri(args[1])
57
58     player = Player(uri)
59     player.run()
60
61 if __name__ == '__main__':
62     sys.exit(main(sys.argv))