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

2024-10-03 02:45:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个在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)

有人知道为什么会这样吗?这个方波函数真的正确吗?在


Tags: 函数eventreturnifvaluedeftypecounter
1条回答
网友
1楼 · 发布于 2024-10-03 02:45:24

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

比较一下:

if counter == length_of_plateau:

这将比较一个整数counter和一个浮点值length_of_plateau。在

length_of_plateau来自此作业:

^{pr2}$

频率为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,而是减去平台的长度(这是一个浮点值)。这意味着在原始代码中引入的舍入错误将随着时间的推移而平滑。在

相关问题 更多 >