devloop random icon
random stuff

python & pulseaudio

Warning: this code is for demonstration purposes only.

I needed to get some information out of pulseaudio and parsing the output of shell commands seemed inelegant (also I wanted to play with ctypes/swig..), this is what I came up with.
You can find a much more complete (and useful) python wrapper in the lib_pulseaudio.py part of gnome-pulse-applet and also in earcandy.
pulsecaster also uses a similar approach.

Using CDLL

Assuming the constants have not changed, you can just run pa-cdll.py.
For now, all it does is list your sinks and sources...

I think this code would be much much nicer using the glib mainloop rather than using a busy wait loop, but I started from this code which does not use it...

Constants: I needed to get some constants from the header file (I could just have assumed that GCC would start the values at 0... but this is more proper): dumpenums.c, compile it gcc -o dumpenums dumpenums.c and run it to check.

Note: I wanted to use the asynchronous API to be able to get deeper into pulseaudio than what is allowed through the simple API, however you may be able to achieve the same (rather simple) results as above through the simple API.

SWIG

I can't see a way of passing the required callbacks to SWIG from python... so I've abandonned this approach.

To build the pulseaudio.py module and its _pulseaudio.so shared library, download pa.swig then run:

swig -python  pa.swig 
gcc -c pa_wrap.c -I /usr/include/python2.6/ -I /usr/include/glib-2.0/ -I /usr/lib64/glib-2.0/include/ -fPIC
gcc -shared pa_wrap.o -o _pulseaudio.so -lpulse -lpulse-simple -lglib -lpulse-mainloop-glib
You should now be able to import the pulseaudio module, test it with:
python -c "import pulseaudio"

(this example is based on my own system's file locations and will probably need to be regenerated/modified - use pkgconfig where appropriate)