[Tutor] How to generate a pure tones and random noise using Python?

Alan Gauld alan.gauld at btinternet.com
Mon Jul 27 01:48:02 CEST 2015


On 25/07/15 12:15, Paul Z wrote:
> Are there some way to generate a fixed frequency sound in different
 > waves (eg. Sine Wave, Saw Wave, Triangle Wave etc.) and
 > different random noise. (eg. white noise & pink noise) ?

While there are several options in Python (check out the
Activestate recipes) the simplest way on Linux may be to
create a file with the relevant signal and then play that
through aplay using the subprocess module.

One such module(by B Walker) that I found on Activestate
is this (slightly tweaked):

def sinebeep():
     header=[ 82, 73, 70, 70, 100, 31, 0, 0, 87, 65, 86, 69,
	     102, 109, 116, 32, 16, 0, 0, 0, 1, 0, 1, 0,
	     64, 31, 0, 0, 64, 31, 0, 0, 1, 0, 8, 0, 100,
	     97, 116, 97, 64, 31, 0, 0 ]
     waveform=[ 79, 45, 32, 45, 79, 113, 126, 113 ]
     wavefile=open("beep.wav", "w+")
	
     for hdr in header:
         wavefile.write(chr(hdr))
     for sample in range(0, 1000, 1):
         for wf in waveform:
             wavefile.write(chr(wf))

     wavefile.close()

if __name__ == '__main__':
     sinebeep()

You can then play the resultant file with

$ aplay beep.wav  #you might need sudo

Its not very clever but you could create a series of beep
files each with a different frequency.

PS.
There is also a command line program called beep that does
what you want but it didn't work for me... YMMV


HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list