#include <gst/gst.h>
#include <gst/gstelement.h>
#include <string.h>  
#include <stdlib.h>
#include <unistd.h>

static gboolean
bus_call_a (GstBus     *bus,
          GstMessage *msg,
          gpointer    data)
{
    GstState state_a;
        GMainLoop *loop = (GMainLoop *) data;
        switch (GST_MESSAGE_TYPE (msg)) {
        case GST_MESSAGE_EOS:
            gst_element_set_state (bin_a, GST_STATE_NULL);
            gst_object_unref (GST_OBJECT (bin_a));
            g_main_loop_quit(loop);
          break;
        case GST_MESSAGE_ERROR: {
          gchar *debug;
          GError *err;
          gst_message_parse_error (msg, &err, &debug);
          g_free (debug);
          g_error_free (err);
          g_main_loop_quit(loop);
          break;
        }
        case GST_MESSAGE_STATE_CHANGED:
            {
            
            
                gst_element_get_state(GST_ELEMENT(bin_a),&state_a,NULL,-1);
                if(state_a == GST_STATE_PLAYING)
                {
                count++;
                 }
          
            }
            break;
        default:
              break;
    }
    
    return TRUE;
    }

static gboolean
quit_loop (gpointer data)
{
    GMainLoop *loop_b = (GMainLoop*)data;
    gst_element_set_state (bin_a, GST_STATE_NULL);
        g_main_loop_quit(loop_b);
    }


void test_record()
    {
    GMainLoop *loop_a;
    GstStateChangeReturn my_state_a;
    GstElement *filesink_a,*filesrc_a;
    GError *error = NULL;
    
    loop_a = g_main_loop_new (NULL, FALSE);
    gst_init (NULL,NULL);
    bin_a = (GstElement *)
        gst_parse_launch ("audiotestsrc ! wavenc ! filesink name=my_filesink", &error);
    
    if (!bin_a) {
        fprintf (stderr, "Parse error: %s", error->message);
        exit (-1);
      }
    filesink_a = gst_bin_get_by_name (GST_BIN (bin_a), "my_filesink");
    g_object_set (G_OBJECT (filesink_a), "location", "~/data/test/audiotest_src.wav", NULL);
    
    gst_bus_add_watch (gst_pipeline_get_bus (GST_PIPELINE (bin_a)), bus_call_a, loop_a);
    /* start playing */
    
    gst_element_set_state (bin_a, GST_STATE_PLAYING);
    g_timeout_add (30000, quit_loop, loop_a);
    g_main_loop_run (loop_a);
    
    
    }
    
    int main()
    {
    test_record();
    return 0;
    }