~vilhalmer/pavc

8f7276a9c7259389ad93e2c769bc3eaec1cc7d41 — Bill Doyle 1 year, 10 days ago
Query volume for default sink
1 files changed, 84 insertions(+), 0 deletions(-)

A pavc.c
A  => pavc.c +84 -0
@@ 1,84 @@
// PulseAudio Volume Control
// It does one thing

#include <pulse/context.h>
#include <pulse/def.h>
#include <pulse/introspect.h>
#include <pulse/mainloop.h>
#include <pulse/proplist.h>
#include <pulse/pulseaudio.h>
#include <pulse/volume.h>
#include <stdio.h>

struct pavc {
	pa_mainloop * loop;

};

static void query_volume_sink(pa_context * ctx, const pa_sink_info * info, int eol, void * userdata) {
	struct pavc * pavc = userdata;
	if (eol) {
		pa_mainloop_quit(pavc->loop, 0);
		return;
	}

	pa_volume_t vol = pa_cvolume_avg(&info->volume);
	char vol_str[1024] = {0};
	pa_volume_snprint(vol_str, 1023, vol);
	printf("volume: %s\n", vol_str);
}

static void state_changed(pa_context * ctx, void * userdata) {
	struct pavc * pavc = userdata;

	switch (pa_context_get_state(ctx)) {
	case PA_CONTEXT_FAILED:
		fprintf(stderr, "Unable to connect to pulseaudio: %s\n", pa_strerror(pa_context_errno(ctx)));
		pa_mainloop_quit(pavc->loop, 2);
		break;
	case PA_CONTEXT_READY:
		// woohoo
		pa_context_get_sink_info_by_name(ctx, "@DEFAULT_SINK@", query_volume_sink, pavc);
		break;
	case PA_CONTEXT_UNCONNECTED:
	case PA_CONTEXT_AUTHORIZING:
	case PA_CONTEXT_CONNECTING:
	case PA_CONTEXT_SETTING_NAME:
	case PA_CONTEXT_TERMINATED:
		// who cares
		break;
	}
}

int main(int argc, char * argv[]) {
	pa_mainloop * loop = pa_mainloop_new();
	assert(loop);

	pa_mainloop_api * api = pa_mainloop_get_api(loop);
	assert(api);

	pa_proplist * properties = pa_proplist_new();
	pa_context * ctx = pa_context_new_with_proplist(api, "pavc", properties);
	assert(ctx);

	assert(pa_context_connect(ctx, NULL, PA_CONTEXT_NOAUTOSPAWN, NULL) >= 0);

	struct pavc pavc = {
		.loop = loop,
	};

	pa_context_set_state_callback(ctx, state_changed, &pavc);

	int exit = 0;
	if (pa_mainloop_run(loop, &exit) < 0) {
		fprintf(stderr, "Unable to communicate with pulseaudio\n");
		exit = 1;
	}

	pa_context_disconnect(ctx);
	pa_context_unref(ctx);
	pa_proplist_free(properties);
	pa_mainloop_free(loop);

	return exit;
}