If one wishes to beep the speaker on Windows, Python 2 apparently provides a useful function: winsound.Beep()
. The neat thing about this function is that it takes arguments specifying the exact frequency and duration of the beep. This is exactly what I want to do, except that I don't use Windows. So...
What are the nearest equivalents of winsound.Beep()
for Linux
and OSX
, bringing in as few dependencies as possible?
Please note that I want to be able to beep the speaker directly, not to play a sound file. Also, I need to be able to control the frequency and duration of the beep, so curses.beep()
and print '\a'
won't do. Lastly, I am aware that PyGame
provides extensive sound capabilities, but given that I don't require any of PyGame's other functionality, that would seem like using a sledgehammer to crack a nut (and anyway, I'm trying to do away with dependencies as far as possible).
5 Answers. Show activity on this post. winsound is only for windows and I could not find any cross platform way to do this, other than print "/a". However, you cannot set the frequency and duration with this.
The winsound module provides access to the basic sound-playing machinery provided by Windows platforms. It includes functions and several constants. winsound. Beep (frequency, duration) Beep the PC's speaker.
winsound is only for windows and I could not find any cross platform way to do this, other than print "/a". However, you cannot set the frequency and duration with this.
However, you can try the os.system command to do the same with the system command beep. Here is a snippet, which defines the function playsound in a platform independent way
try: import winsound except ImportError: import os def playsound(frequency,duration): #apt-get install beep os.system('beep -f %s -l %s' % (frequency,duration)) else: def playsound(frequency,duration): winsound.Beep(frequency,duration)
For more info, look at this blog
EDIT: You will need to install the beep package on linux to run the beep command. You can install by giving the command
sudo apt-get install beep
I found a potential solution here: http://bytes.com/topic/python/answers/25217-beeping-under-linux
It involves writing directly to /dev/audio. Not sure how portable it is or if it even works at all - i'm not on a linux machine atm.
def beep(frequency, amplitude, duration): sample = 8000 half_period = int(sample/frequency/2) beep = chr(amplitude)*half_period+chr(0)*half_period beep *= int(duration*frequency) audio = file('/dev/audio', 'wb') audio.write(beep) audio.close()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With