Skip to main content
 首页 » 编程设计

Python 方波函数之这里发生了什么

2024年10月25日11lidabo

我有一个在 python 中创建方波的函数,但我似乎无法从中发出声音,但是当我更改它时:

value = state * volume 
s.append( [value, value] ) 

为此:

value = state * volume 
s.append( [0, value] ) 

我听到了一个声音,但它的频率比我打算产生的 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) 

谁能看出为什么会这样?这个方波函数真的正确吗?

请您参考如下方法:

问题的原因很可能是因为您没有正确考虑浮点值。

进行比较:

if counter == length_of_plateau: 

这会将整数 counter 与浮点值 length_of_plateau 进行比较。

length_of_plateau 来自这个作业:

length_of_plateau = SAMPLE_RATE / (2*freq) 

频率为 130.81,采样率为 44100(我在这里猜测,您没有发布 SAMPLE_RATE 的值是多少),您会得到:

length_of_plateau = 168.565094412 

因此,整数永远不会等于该值。

相反,我会这样做:

state = 1 
next_plateau_end = length_of_plateau 
 
counter = 0 
for n in range(num_steps): 
    value = state * volume 
    s.append( [value, value] ) 
 
    if counter >= next_plateau_end: 
        counter -= length_of_plateau 
        state *= -1 
    counter += 1 

我们不是每次都将 counter 重置为 0,而是减去 plateau 的长度(这是一个浮点值)。这意味着原始代码中引入的舍入误差将随着时间的推移而被消除。