Sine wave?

Tim Roberts timr at probo.com
Sun Dec 22 15:43:15 EST 2002


"EC" <vitamonkey at home.com> wrote:
<
>Ive been banging my head against the wall for the past few days trying to
>generate a sine wave... My math skills arent the best, I'll admit, and I
>think I'm going crosseyed trying to understand this... I *think* the
>following code should work but it outputs some really weird stuff.  I'm
>sorta new so please help if you can! Thank you

First, wave.writeframes needs to get binary data.  You're feeding it a big,
long string that looks like "-14223,-11929,-5959," etc.  You should
probably take your list of integers (Outtemp) and convert it to an array
using the array module:

   Outfile.writeframes(array.array("h",Outtemp).tostring())

Next, your conversion from degrees to radians is wrong:
        t = int(round(amp*sin(2*pi*curphase)))
that should be:
        t = int(round(amp*sin(2*pi*curphase/360)))

It might be easier if you just changed get_phase to produce radians
instead.

That should produce the results you want.  You'll need to produce a bit
more than .01 seconds to hear the result.

"phinc" is a constant; you should probably just precompute it instead of
computing it for every loop.


def get_phase(curphs, freq):
    phinc = (freq*1.0000/sr*1.0000)*2*pi
    phase = (curphs + phinc)
    if phase > 2*pi: 
	phase -= 2*pi
    return phase

def gen_wav(sec, freq, ampcent):
    numsamp = sec*sr
    amp = (ampcent*1.0000/100)*32767
    temp = []
    curphase = 0
    for i in range(numsamp):
        curphase = get_phase(curphase, freq)
        t = int(round(amp*sin(curphase)))
        temp.append(t)
    return temp

Outtemp = gen_wav(1, 440, 75)
Outfile.writeframes(array.array('h',Outtemp).tostring())
Outfile.close()

#Outstr = string.join(map(str, Outtemp), ",")
#print Outstr
--
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.



More information about the Python-list mailing list