python: update python examples to modern python, Gst, and Glib versions
[experiments/gstreamer.git] / python / gst-player-example.py
1 #!/usr/bin/env python3
2 #
3 # Player - a very simple media player based on GstPlayer
4 #
5 # Copyright (C) 2016  Antonio Ospite <ao2@ao2.it>
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20 import sys
21 import gi
22
23 gi.require_version('Gst', '1.0')
24 from gi.repository import Gst
25 Gst.init(None)
26
27 gi.require_version('GstPlayer', '1.0')
28 from gi.repository import GstPlayer
29
30 from gi.repository import GLib
31
32
33 class Player(object):
34     def __init__(self):
35         self.player = GstPlayer.Player.new(signal_dispatcher=GstPlayer.PlayerGMainContextSignalDispatcher())
36         self.player.connect("error", self.error_cb)
37         self.player.connect("end-of-stream", self.end_of_stream_cb)
38         self.player.connect("state-changed", self.state_changed_cb)
39
40         self.mainloop = GLib.MainLoop()
41
42     def end_of_stream_cb(self, player):
43         self.mainloop.quit()
44
45     def error_cb(self, player, error):
46         print(error)
47         self.mainloop.quit()
48
49     def state_changed_cb(self, player, state):
50         print(state)
51
52     def play(self, filename):
53         self.player.set_uri(Gst.filename_to_uri(filename))
54         self.player.play()
55         self.mainloop.run()
56
57     def stop(self):
58         self.player.stop()
59         self.mainloop.quit()
60
61
62 def main():
63     if len(sys.argv) > 1:
64         player = Player()
65         try:
66             player.play(sys.argv[1])
67         except KeyboardInterrupt:
68             player.stop()
69
70
71 if __name__ == "__main__":
72     main()