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

Re: [pygame] noob questions about creating and playing sounds



On Mon, Jul 20, 2009 at 9:55 AM, Yanom Mobis<yanom@xxxxxxxxxxxxxx> wrote:
> code gets all gibberishy in the message itself attatch the .py file(s) to
> the message

Oops, sorry, I didn't know that!
I forgot to mention, that I am running Python 2.6.6 under Linux. I can
provide further information if necessary.
#! /usr/bin/env python

import numpy
import pygame

# Create the sound wave in the required bit-rate.
def sine_array(freq, amplitude, sample_rate):
    wavelength = sample_rate / freq
    omega = 2 * numpy.pi / wavelength
    xvalues = numpy.arange(wavelength) * omega
    return numpy.int16(amplitude * numpy.sin(xvalues))

# Two different methods for playing the sound.
def play_maxtime(sound, duration):
    sound.play(loops=-1, maxtime=duration)
    pygame.time.delay(duration)

def play_loops(sound, duration):
    sound.play(loops=-1)
    pygame.time.delay(duration)
    sound.stop()

# Initialize PyGame & PyGame sound system.
sample_rate, bit_rate, channels = 22050, -16, 1
pygame.mixer.pre_init(sample_rate, bit_rate, channels)
pygame.init()
sample_rate, bit_rate, channels = pygame.mixer.get_init()
assert bit_rate == -16   # sine_array only implements 16 bit signed
pygame.sndarray.use_arraytype('numpy')

# Create a sound array, and convert it to a Sound object.
sound_array = sine_array(440, 20000, sample_rate)
sound = pygame.sndarray.make_sound(sound_array)

# Play the sound using two different methods.
duration = 2000
play_maxtime(sound, duration)
pygame.time.delay(duration)
play_loops(sound, duration)