我有一个在python中创建方波的函数,我似乎无法从中获得声音,但当我更改此函数时:
value = state * volume
s.append( [value, value] )
为此:
^{pr2}$我听到一个声音,但是它的频率比我想要的130.81频率要高得多。以下是完整代码:
def SquareWave(freq=1000, volume=10000, length=1):
num_steps = length * SAMPLE_RATE
s = []
length_of_plateau = SAMPLE_RATE / (2*freq)
counter = 0
state = 1
for n in range(num_steps):
value = state * volume
s.append( [value, value] )
counter += 1
if counter == length_of_plateau:
counter = 0
state *= -1
return numpy.array(s)
def MakeSound(arr):
return pygame.sndarray.make_sound(arr)
def MakeSquareWave(freq=1000):
return MakeSound(SquareWave(freq))
调用这些函数的代码块如下:
elif current_type == SQUARE_WAVE_TYPE:
if event.type == KEYDOWN:
#lower notes DOWN
if event.key == K_z:
print current_type, 130.81
#current_played['z'] = MakeSineWave(80.81)
current_played['z'] = MakeSquareWave(130.81)
current_played['z'].play(-1)
elif event.key == K_c:
print current_type, 180.81
#current_played['c'] = MakeSineWave(80.81)
current_played['c'] = MakeSquareWave(180.81)
current_played['c'].play(-1)
有人知道为什么会这样吗?这个方波函数真的正确吗?在
问题的原因很可能是因为没有正确考虑浮点值。在
比较一下:
这将比较一个整数
counter
和一个浮点值length_of_plateau
。在
^{pr2}$length_of_plateau
来自此作业:频率为130.81,采样率为44100(我猜,您没有发布sample_rate的值),您可以得到:
所以,一个整数永远不会等于那个值。在
相反,我要做的是:
我们不是每次都将
counter
重置为0,而是减去平台的长度(这是一个浮点值)。这意味着在原始代码中引入的舍入错误将随着时间的推移而平滑。在相关问题 更多 >
编程相关推荐