Friday, November 12, 2010

Getting the default volume from PulseAudio in C

I have been screwing around with trying to find out how to get the default volume from PulseAudio for the longest time. I finally got it working in a GTK application by reading the pavucontrol applications code. Since this was such a pain for me to find, I thought I would share it.

In your make sure you have these lines

PKG_CHECK_MODULES(PULSE, [libpulse libpulse-mainloop-glib])

Then make sure in your you have $(PULSE_CFLAGS) in the INCLUDES and $(PULSE_LIBS) in appname_LDADD. These may vary in your setup, but that should work for automake projects.

The code...

#include "gtk/gtk.h"
#include "pulse/pulseaudio.h"
#include "pulse/glib-mainloop.h"

void pa_sink_info_callback(pa_context *context, const pa_sink_info *i, int eol, gpointer data)
    if (i != NULL) {
        //printf("channels = %i\n", i->volume.channels);
        //printf("raw volume = %i\n", pa_cvolume_avg(&(i->volume)));
        //printf("linear volume = %f\n", pa_sw_volume_to_linear(pa_cvolume_avg(&(i->volume))));
        printf("percent volume = %f\n", (gdouble)pa_cvolume_avg(&(i->volume)) / (gdouble)PA_VOLUME_NORM);

void pa_server_info_callback(pa_context *context, const pa_server_info *i, void *userdata)
    //printf("server info\n");
    printf("default sink name = %s\n",i->default_sink_name);
    pa_context_get_sink_info_by_name(context,i->default_sink_name, pa_sink_info_callback, NULL);

void context_state_callback(pa_context *context, void *userdata)
    //printf("context state callback\n");
    switch (pa_context_get_state(context)) {
        case PA_CONTEXT_READY: {



int main(int argc, char *argv[]) {
    pa_glib_mainloop *loop = pa_glib_mainloop_new(g_main_context_default());
    pa_context *context = pa_context_new(pa_glib_mainloop_get_api(loop),"test");                             
    pa_context_connect(context, NULL, 0 , NULL);
    pa_context_set_state_callback(context, context_state_callback, NULL);
    return 1;

No comments: