On the other day, I decided to add a sound notification to my unity pomodoro applet and I did a little research. Turns out there are a few options to do this, but not many examples on the internet. And some of those options depend heavily on the operating system and the installation of external modules.
So I ended up being grateful, again, for the invention of Stack Overflow!
from os import popen popen("canberra-gtk-play --file=" + os.path.join(os.path.dirname(os.path.realpath(__file__)), 'sounds/sound.ogg') + " > /dev/null 2>&1 || true")
(NOTE: This solution is Linux specific, but I selected it because since canberra-gtk-play comes installed by default with Ubuntu and I didn’t want that people had to install external modules to use the applet)
Now, let’s break down this solution!
Basically, we are using popen() to run canberra-gtk-play command. You can try the following command in your terminal (may not work if you’re not on Ubuntu):
And then we just use the os.path functions to get the relative path to our application sounds instead of hardcoding them.
Lastly the addition of
> /dev/null 2>&1 || true
in front of the command is just to prevent error outputs in case the command or the sound file is not found in the user’s system (don’t use it in development and testing so you can check for errors).
(NOTE: I have written “(python)” with parenthesis in the title because this solution it’s based on a command line execution, which mean you can use it with any language that allows you to run a command line.)
There are a few other options that use modules like winsound, pygame and mp3play. You can check them out here.