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

Re: [pygame] Screeching, Howling Garbage in One Ear pygame.sndarray



Hey, Pete!
How's life treating you?
I'm getting some distortion in the channels with your example too.
it's a popping noise just like Andrew's example.



Peter Shinners wrote:
On Thu, 2006-05-04 at 23:52 -0700, andrew baker wrote:
I'm trying to build a stereo tone generator module. It sort of works,
but I'm getting hellacious garbage noise in the left channel.

I whipped a tone generator up. It started kind of simple, but then I decided to make it work for any type of configuration.

------------------------------------------------------------------------

#!/usr/bin/env python
"""
Example tone generation program for pygame
Pete Shinners
May 5, 2006
Public Domain
"""
USAGE = """USAGE: %s <rate (hz)> <length (secs)>"""

import sys, math, pygame, Numeric



def Main(args):
    try:
        rate = float(args[1])
        length = float(args[2])
    except StandardError:
        print USAGE % (args[0])
        sys.exit(1)
    pygame.mixer.init()
    tone = MakeTone(rate, length)
    tone.play()
    while pygame.mixer.get_busy():
        pygame.time.wait(100)



def MakeTone(rate, length):
    freq, format, stereo = pygame.mixer.get_init()
    size = int(freq * length)
    mult = rate / freq * math.pi * 2
    ramp = Numeric.arange(0, size, 1, Numeric.Float)
    tone = Numeric.sin(ramp * mult)
    samples = FloatToFormat(tone, format, stereo)
    return pygame.sndarray.make_sound(samples)



def FloatToFormat(data, format, stereo):
    if abs(format) == 16:
        if format < 0:
            samples = ((data-0.5) * 0xffff).astype(Numeric.Int16)
        else:
            samples = (data * 0xffff).astype(Numeric.UInt16)
    else:
        if format < 0:
            samples = ((data-0.5) * 0xff).astype(Numeric.Int8)
        else:
            samples = (data * 0xff).astype(Numeric.UInt8)
    if stereo:
        mono = samples
        samples = Numeric.zeros((data.shape[0], 2), mono.typecode())
        samples[:] = mono[:,Numeric.NewAxis]
    return samples



if __name__ == "__main__":
    Main(sys.argv)