Python 方波函数 - 这是怎么回事?

标签 python audio numpy pygame

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

关于Python 方波函数 - 这是怎么回事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24895067/

相关文章:

numpy - 意外的 scipy.stats.uniform 行为

python - 使用 Lisp/Scheme 作为脚本语言是否可行?

python - 如何通过对前一行和当前行的值求和来填充 PySpark Dataframe 的行?

java - Java boolean 播放按钮问题(每次单击一次又一次播放)

java - 尝试使用javax.sound注册语音

python - 如何在 python : numpy. Mean() 中将多个列表合并为一个列表

python - 在 Python 中使用 Lambda 追加或扩展

python - 如何使用python在Excel单元格中显示嵌入的文本文件

audio - 通过互联网将音频从位置1传输到位置2

python - 如何就地转置 numpy ndarray?