如何使用 Pygame 播放 sine/square 波?

How can I play a sine/square wave using Pygame?

我正在尝试使用 Pygame 的 sndarray.make_sound 函数播放正弦波。但是,当我使用这个数组播放它时:

np.sin(2 * np.pi * np.arange(44100) * 440 / 44100).astype(np.float32)

其中 440 是频率,44100 是采样率,而是播放响亮、刺耳的噪音。这可以使用 pyaudio.PyAudio(),但是我需要一些不会阻止执行的东西。方波也会发生这种情况,但是它只是不播放任何东西。我将 channels=1 用于 mixer.pre_initmixer.init 函数。

我该如何解决这个问题?如果有帮助,我正在使用 Mac。提前致谢!

您可以将 numpy 数组直接加载到 pygame.mixer.Sound object and play 它。出现刺耳的声音是因为您可能正在向混音器发送 32 位浮点样本,而它期望 16 位整数样本。如果要使用 32 位浮点数数组,则必须将 mixer 的 init 函数的 size 参数设置为 32:

import pygame
import numpy as np

pygame.mixer.init(size=32)

buffer = np.sin(2 * np.pi * np.arange(44100) * 440 / 44100).astype(np.float32)
sound = pygame.mixer.Sound(buffer)

sound.play(0)
pygame.time.wait(int(sound.get_length() * 1000))