python: update python examples to modern python, Gst, and Glib versions
[experiments/gstreamer.git] / python / gst-looping-video-2.py
1 #!/usr/bin/env python3
2 #
3 # A simple looping player.
4 # Version 2, based on "about-to-finish" 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._uri = uri
22         self._player = Gst.ElementFactory.make("playbin3", "player")
23         self._player.set_property("uri", uri)
24         self._player.connect("about-to-finish", self.on_about_to_finish)
25
26         bus = self._player.get_bus()
27         bus.add_signal_watch()
28         bus.connect('message::error', self.on_error)
29
30     def run(self):
31         self._player.set_state(Gst.State.PLAYING)
32         self.loop = GLib.MainLoop()
33         self.loop.run()
34
35     def quit(self):
36         self._player.set_state(Gst.State.NULL)
37         self.loop.quit()
38
39     def on_about_to_finish(self, player):
40         sys.stderr.write(".")
41         player.set_property("uri", self._uri)
42
43     def on_error(self, bus, msg):
44         (err, debug) = msg.parse_error()
45         print("Error: %s" % err, debug)
46         self.quit()
47
48
49 def main(args):
50     def usage():
51         sys.stdout.write("usage: %s <filename>\n" % args[0])
52
53     if len(args) != 2:
54         usage()
55         sys.exit(1)
56
57     uri = Gst.filename_to_uri(args[1])
58
59     player = Player(uri)
60     player.run()
61
62 if __name__ == '__main__':
63     sys.exit(main(sys.argv))