Python Sound ("Bell")
I'd like to have a python program alert me when it has completed its task by making a beep noise. Currently, I use import os
and then use a command line speech program to say "Process complete". I much rather it be a simple "bell."
I know that there's a function that can be used in Cocoa apps, NSBeep
, but I don't think that has much anything to do with this.
I've also tried
print(\a)
but that didn't work.
I'm using a Mac, if you couldn't tell by my Cocoa comment, so that may help.
Have you tried :
import sys
sys.stdout.write('\a')
sys.stdout.flush()
That works for me here on Mac OS 10.5
Actually, I think your original attempt works also with a little modification:
print('\a')
(You just need the single quotes around the character sequence).
If you have PyObjC (the Python - Objective-C bridge) installed or are running on OS X 10.5's system python (which ships with PyObjC), you can do
from AppKit import NSBeep
NSBeep()
to play the system alert.
I tried the mixer from the pygame module, and it works fine. First install the module:
$ sudo apt-get install python-pygame
Then in the program, write this:
from pygame import mixer
mixer.init() #you must initialize the mixer
alert=mixer.Sound('bell.wav')
alert.play()
With pygame you have a lot of customization options, which you may additionally experiment with.
I had to turn off the "Silence terminal bell" option in my active Terminal Profile in iTerm for print('\a')
to work. It seemed to work fine by default in Terminal.
You can also use the Mac module Carbon.Snd
to play the system beep:
>>> import Carbon.Snd
>>> Carbon.Snd.SysBeep(1)
>>>
The Carbon modules don't have any documentation, so I had to use help(Carbon.Snd)
to see what functions were available. It seems to be a direct interface onto Carbon, so the docs on Apple Developer Connection probably help.
Building on Barry Wark's answer...
NSBeep()
from AppKit works fine, but also makes the terminal/app icon in the taskbar jump.
A few extra lines with NSSound()
avoids that and gives the opportunity to use another sound:
from AppKit import NSSound
#prepare sound:
sound = NSSound.alloc()
sound.initWithContentsOfFile_byReference_('/System/Library/Sounds/Ping.aiff', True)
#rewind and play whenever you need it:
sound.stop() #rewind
sound.play()
Standard sound files can be found via commandline locate /System/Library/Sounds/*.aiff
The file used by NSBeep()
seems to be '/System/Library/Sounds/Funk.aiff'