Sine wave?

Andrew Henshaw andrew.henshaw at gtri.gatech.edu
Mon Dec 23 00:09:52 EST 2002


Bengt Richter wrote:

> On Sun, 22 Dec 2002 13:42:19 -0500, "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
>>
>>Eric
... code snipped ...

>>
> Try this ( just run  python sinewave.py and it should generate 2 seconds
> of 2khz at 75% amplitude that you can listen to with media player.
> Also will plot the first 34 samples on console screen, self-scaling
> when it exceeds the display region (right away here). See after this.
> My media player didn't like 4-byte samples, so that was changed, among
> other things ;-)
> 
... code and curve snipped
> Regards,
> Bengt Richter

The original poster might also be interested in the following version (based 
upon Bengt's code) that uses the Numeric module for speed and code economy.

####################################################
from Numeric import floor, arange, sin, pi
import wave

#init output and related vars
samplesPerSecond = 44100
Outfile = wave.open("outfile.wav", "w")
Outfile.setnchannels(1)
Outfile.setsampwidth(2) # 2 bytes for 32767 amplitude
Outfile.setframerate(samplesPerSecond)
Outfile.setcomptype("NONE", "Uncompressed")

def gen_wav(seconds, frequency, amplitudePercentOfMax):
    # calculate frequency as radians/sample
    radiansPerSample = (2.0 * pi * frequency) / samplesPerSecond 
    numberOfSamples  = int(seconds*samplesPerSecond)
    maxAmplitude     = (amplitudePercentOfMax / 100.0) * 32767
    samples = sin(arange(numberOfSamples) * radiansPerSample) * maxAmplitude
    # round and convert to array of 16-bit shorts
    return floor(samples + 0.5).astype('s')

if __name__ == '__main__':
    sampleArray = gen_wav(2, 2000, 75)
    Outfile.writeframes(sampleArray.tostring())  # little-endian cpu only
    Outfile.close()


--Andy



More information about the Python-list mailing list