Playing system sounds from Python programs on Ubuntu

Jono asked me yesterday how you play a system beep from a Python program on Ubuntu. Now, the way you’re meant to play system sounds is by using libcanberra; it’s the standard platform library for playing a sound. Sounds come from your sound theme.

A sidebar: themes in Ubuntu

The icons used by your desktop are part of an icon theme. This means that there are a set of names defined for particular things — there’s an icon name for “sound at maximum volume”, another name for “sound at minimum volume”, another for “wireless network connected”, and so on. Then the applications on the desktop use those icons by name, so the Sound indicator displays the “sound at maximum volume” icon in the panel at the top of the screen when your sound’s at maximum volume. This means that you can change the look of your desktop by providing a different icon theme (a whole set of icons, named after the specified names), and all your applications use your new icons so they all look consistent. A sound theme works on the same principle; there are a defined set of sounds (there’s one for “your battery is low”, one for “a window has been maximised”, one for “you have logged in”, and so on), and your sound theme defines what those sounds are. So you can switch in a different sound theme, and now all your applications will change to use the sounds from your sound theme. End of sidebar.

What all this boils down to is that you ought to be able to play the standard warning sound by telling libcanberra to “play a sound named dialog-warning, and it’ll play the correct sound.

However, there isn’t a Python version of libcanberra, sad to say. I complained about this on twitter, and psykoyiko brilliantly responded with a pointer to a Python libcanberra library he wrote: pycanberra.py. So, you can now play system sounds from your Python program, because this is basically a set of Python bindings for libcanberra.

To play a sound:

import pycanberra
canberra = pycanberra.Canberra()
canberra.easy_play_sync("dialog-warning")
canberra.destroy()

Hooray! Good job psykoyiko! Someone should get this into Ubuntu.

More in the discussion (powered by webmentions)

  • (no mentions, yet.)