#!/usr/bin/python

import pygst
pygst.require("0.10")

import glib
import gst

def handle_eos(bus, message, loop):

    print "EOS"
    loop.quit()

def toggle_state(pipe):

    ret, state, pending = pipe.get_state(gst.CLOCK_TIME_NONE)

    if ret != gst.STATE_CHANGE_SUCCESS:
        return False

    if state == gst.STATE_PLAYING:
        print "pausing"
        gst.log("pausing")
        pipe.set_state(gst.STATE_PAUSED)
    elif state == gst.STATE_PAUSED:
        print "playing"
        gst.log("playing")
        pipe.set_state(gst.STATE_PLAYING)
    else:
        return False

    return True

def main():

    loop = glib.MainLoop()
    pipe = gst.parse_launch("audiotestsrc num-buffers=50 ! "
                            "pulsesink latency-time=100000 buffer-time=500000")
    bus = pipe.get_bus()
    bus.add_signal_watch()
    bus.connect("message::eos", handle_eos, loop)

    glib.timeout_add(250, toggle_state, pipe)

    try:
        pipe.set_state(gst.STATE_PLAYING)
        loop.run()
    finally:
        pipe.set_state(gst.STATE_NULL)

main()
