Am Fri, 30 Dec 2011 07:17:13 +0000 schrieb Paulo da Silva:
Hi,
Sorry if this is a FAQ, but I have googled and didn't find any
satisfatory answer.
Is there a simple way, preferably multiplataform (or linux), of
generating sinusoidal/square waves sound in python?
Thanks for any answers/suggestions.
Have a look at the wave module, available under Windows and Linux,
which operates on .WAV files. The following snippet might get you going:
#!/usr/bin/python
import math, wave, struct
def signal(t, freq):
return math.sin(2.0*math.pi*freq*t)
wout = wave.open("sample.wav", "wb")
nchan = 1
sampwidth = 2
framerate = 8000
nframes = 7 * framerate
comptype = "NONE"
compname = "no compression"
wout.setparams((nchan, sampwidth, framerate, nframes, comptype, compname))
ts = 1.0 / framerate
t = 0.0
n = 0
data = []
vals = []
while n < nframes:
vals.append(signal(t, 517.0))
n = n + 1
t = t + ts
mx = max((abs(x) for x in vals))
vals = [ x/mx for x in vals ]
data = ""
for v in vals:
data = data + struct.pack("<h", int(v*32766.0))
wout.writeframes(data)
wout.close()
Alternatively you might just generate (t,signal) samples, write them to
a file and convert them using "sox" (under Linux, might also be available
under Windows) to another format.
HTH
Martin