[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] playing a pure tone from Numeric array



On Wednesday, Aug 6, 2003, at 16:46 America/New_York, John Hunter wrote:

I am trying to use pygame to create sound arrays with Numeric.  When I
try and play the sound, no sound comes out.  Here is what I am doing:

    from Numeric import *
    from pygame import mixer, sndarray, time

    mixer.init(22050, 16, 0)

    phi = arange(44100) / 4.0
    s = sin(phi).astype(Int16)
    snd = sndarray.make_sound(s)
    snd.play()

    while mixer.get_busy():
        time.wait(200)
Well, your math is completely bogus. Take a look:

phi = arange(44100) # [0, 1, ...., 44099] typecode = 'l', signed 32bit integer
phi /= 4.0 # [0, 0.25, ...., 11024.75] typecode = 'd', 64bit floating point
s = sin(phi) # [-1.0 <= values <=1.0] typecode = 'd', 64bit floating point
s = s.astype(Int16) # [0, 0, ...., 0] typecode = 'h', signed 16bit integer

Now you have a big fat array of zeros. It's making exactly the sound you asked it to ;)

What you probably wanted was something like this:

from Numeric import *
from pygame import mixer, sndarray, time
from math import pi
seconds = 1.0
samplerate = 22050.0 # hz
frequency = 261.63 # hz, C4
bits = 16
pygame.init()
mixer.init(int(samplerate), bits, 0)
samples = (sin(arrayrange(seconds * samplerate) * (2 * pi * (frequency / samplerate))) * float(1 << (bits - 1))).astype(Int16)
snd = sndarray.make_sound(samples)
snd.play()
while mixer.get_busy():
time.wait(200)

I'm not entirely sure this is correct, cause I haven't tested it and I don't have perfect pitch or anything.. but it should be a lot closer ;)

-bob