#!/usr/bin/python

import sys, os

from gi.repository import GObject, GLib, Gst

Gst.init(None)

uri = "file:///home/lazka/foo/a.mp3"

def about_to_finish(player):
    print "about to finish, set next song"
    player.set_property("uri", uri)

player = Gst.ElementFactory.make("playbin", "player")
sink = Gst.ElementFactory.make("autoaudiosink", "sink")
pitch = Gst.ElementFactory.make("pitch", "pitch")

bufbin = Gst.Bin()
bufbin.add(sink)
bufbin.add(pitch)

gpad = Gst.GhostPad.new('sink', pitch.get_static_pad('sink'))
bufbin.add_pad(gpad)
pitch.link(sink)

player.connect('about-to-finish', about_to_finish)
player.set_property("uri", uri)
player.set_property('audio-sink', bufbin)


def start():
    print "start"
    player.set_state(Gst.State.PLAYING)
    player.get_state(Gst.SECOND * 100)
    ok, duration = player.query_duration(Gst.Format.TIME)

    print "seek to 5 seconds before the song finishes"
    event = Gst.Event.new_seek(
                1.0, Gst.Format.TIME, Gst.SeekFlags.FLUSH,
                Gst.SeekType.SET, duration - Gst.SECOND * 5,
                Gst.SeekType.NONE, 0)
    player.send_event(event)

def print_position():
    print player.get_state(Gst.SECOND * 100)[1].value_name,
    ok, pos = player.query_position(Gst.Format.TIME)
    print pos / Gst.SECOND,
    print player.get_property("uri")
    return True

GLib.idle_add(start)
GLib.timeout_add(1000, print_position)

GObject.threads_init()

loop = GLib.MainLoop()
loop.run()

