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

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



.play() with no arguments just plays the whole sound once. 

I fixed the problem, I think.  The issue is in the way the sound is created.  There's sometimes a bit of static-ey stuff in there on my system which I don't have time to track down right now.  Hope it helps,

Ian
#! /usr/bin/env python

import numpy
import pygame

# Create the sound wave in the required bit-rate.
def sine_array(freq, amplitude, sample_rate):
    #length, in samples, of a single wave
    wavelength = float(sample_rate)/float(freq)
    #scale of 0.0 to 1.0
    samples = numpy.array(numpy.arange(sample_rate+1),"f")/float(sample_rate)
    #how many repeats of the wave
    repeats = sample_rate/wavelength
    #radians
    omega = repeats*2.0*numpy.pi
    #sinusoidal samples
    samples = sample_rate*amplitude*numpy.sin(samples*omega)
    #convert to bitrate
    samples = numpy.array(samples,"int16")
    #return
    return samples

# 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()
pygame.sndarray.use_arraytype('numpy')

# Create a sound array, and convert it to a Sound object.
sound_array = sine_array(440, 1.0, 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)