如何使用 Pygame 播放正弦/方波? [英] How can I play a sine/square wave using Pygame?
问题描述
我正在尝试使用 Pygame 的 sndarray.make_sound
函数播放正弦波.但是,当我使用这个数组播放时:
I'm trying to play a sine wave using Pygame's sndarray.make_sound
function. However, when I use this array to play it:
np.sin(2 * np.pi * np.arange(44100) * 440/44100).astype(np.float32)
其中 440
是频率,44100
是采样率,而是播放响亮的刺耳噪音.这使用 pyaudio.PyAudio()
工作,但是我需要一些不会阻止执行的东西.方波也会发生这种情况,但是在那里它没有播放任何内容.我将 channels=1
用于 mixer.pre_init
和 mixer.init
函数.
where 440
is the frequency and 44100
is the sample rate, a loud, jarring noise plays instead. This works using pyaudio.PyAudio()
, however I need something that doesn't block execution. This happens with square waves, too, however there it just doesn't play anything. I'm using channels=1
for the mixer.pre_init
and mixer.init
functions.
我该如何解决这个问题?如果有帮助,我正在使用 Mac.提前致谢!
How can I fix this? If it helps, I'm using a Mac. Thanks in advance!
推荐答案
您可以将 numpy 数组直接加载到 pygame.mixer.Sound
对象和 play
它:
You can load the numpy array directly to a pygame.mixer.Sound
object and play
it:
import pygame
import numpy as np
pygame.mixer.init()
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))
这篇关于如何使用 Pygame 播放正弦/方波?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!