[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]
[pygame] Sine Waves
It's driving me nuts: why is this not producing a sine wave at the
specified frequency? I get an ugly, rasping beep that doesn't sound at
all like the sample at
<http://www.sfu.ca/sonic-studio/handbook/Sine_Wave.html>, and sounds
like a different frequency than the square waves produced by the
function below. Calling "SineWave(100)[:220]" seems to show data that
repeats every 220 cycles, ie. 100 times per second at the specified
sample rate, yet it still doesn't sound right.
Kris
import pygame, math
from Numeric import *
SAMPLE_RATE = 22050 ## This many array entries == 1 second of sound.
pygame.init()
def SineWave(freq=1000,volume=100000,length=1):
num_steps = length*SAMPLE_RATE
s = []
for n in range(num_steps):
value = int(math.sin(n * freq * (6.28318/SAMPLE_RATE) * length
)*volume)
s.append( [value,value] )
x_arr = array(s)
return x_arr
def SquareWave(freq=1000,volume=100000,length=1):
length_of_plateau = SAMPLE_RATE / (2*freq)
s = []
counter = 0
state = 1
for n in range(length*SAMPLE_RATE):
if state == 1:
value = volume
else:
value = -volume
s.append( [value,value] )
counter += 1
if counter == length_of_plateau:
counter = 0
if state == 1:
state = -1
else:
state = 1
x_arr = array(s)
return x_arr
def MakeSound(arr):
return pygame.sndarray.make_sound(arr)
def PlaySquareWave(freq=1000):
MakeSound(SquareWave(freq)).play()
def PlaySineWave(freq=1000):
MakeSound(SineWave(freq)).play()