Generating Tones With Python

Tim Harig usernet at ilthio.net
Mon May 18 08:33:59 CEST 2009


On 2009-05-18, Adam Gaskins <agaskins_ng at kelleramerica.com> wrote:
> I am pretty sure this shouldn't be as hard as I'm making it to be, but 
> how does one go about generating tones of specific frequency, volume, and 
> L/R pan? I've been digging around the internet for info, and found a few 

This can be done with SDL which would be my first suggestion.
There doesn't seem to be a direct Python SDL module but pygame seems to
encompass the SDL interface.  If that doesn't work for you might be able
to write python wrappers and the C SDL functions.

A second option, on Windows, may be to interface DirectX.  This would not
be cross platform and I don't personally know anything about it; but, it
should be possible to work with DirectX.  I found this with a Google
search:

http://directpython.sourceforge.net/


Finally, if all else fails you can generate the PCM directly and pipe it to
an external interface.  I have never actually written anything that
actually output sounds directly; but, I have written a module to generate
morse tones wave files:

info:
	http://ilthio.net/page.cgi?doc=n20
script:
	http://ilthio.net/page.cgi?txt=cw.py

Look inside of the oscillator class.  I used an 8bit samplewidth with
1 channel to save space (I originally did implement it in 16bit mono).
To do more complex sounds, you will probably need to a 16 bit channel.
Note that 8bit wave files use unsigned integer values, little endian while
16 bit wave files use signed integers, little endian, two's compliment.
For L/R pan, you will also need to create the second channel waveform.  You
can easily find good references for the different wave file PCM formats
with a search engine query.

If the SDL interface doesn't work for you, then you might be able to
generate a PCM format and pipe it to an external player.  In this scenerio
you would likely ignore actually creating the wave file.  You would instead
just create the raw PCM format inside of the array container and then
pipe bits of it out to the wave player program.  Without the format data
contained in the RIFF header of the wave file, you will need to inform
the player as to exactly what format you will be feeding it.  Most Unix
players have command line options that will allow you to specify the
format.  I am not sure whether Windows based players allow similar
options.  Under Linux, you could pipe the stream directly to the sound
card device inteface file in the /dev filesystem if you know what bitrate
the soundcard uses internally.

This would likely require a second process or second thread to make sure
that you can feed the PCM output in real time.



More information about the Python-list mailing list