Python: what are the nearest Linux and OSX equivalents of winsound.Beep? Python: what are the nearest Linux and OSX equivalents of winsound.Beep? linux linux

Python: what are the nearest Linux and OSX equivalents of winsound.Beep?


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 winsoundexcept 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()


This works on mac:

import numpy as npimport simpleaudio as sadef sound(x,z): frequency = x # Our played note will be 440 Hz fs = 44100  # 44100 samples per second seconds = z  # Note duration of 3 seconds # Generate array with seconds*sample_rate steps, ranging between 0 and seconds t = np.linspace(0, seconds, seconds * fs, False) # Generate a 440 Hz sine wave note = np.sin(frequency * t * 2 * np.pi) # Ensure that highest value is in 16-bit range audio = note * (2**15 - 1) / np.max(np.abs(note)) # Convert to 16-bit data audio = audio.astype(np.int16) # Start playback play_obj = sa.play_buffer(audio, 1, 2, fs) # Wait for playback to finish before exiting play_obj.wait_done()sound(300,2)sound(200,1)