Python 用于实时合成的pygame声音模块
有一个pythonPython 用于实时合成的pygame声音模块,python,audio,pygame,buffer,synthesis,Python,Audio,Pygame,Buffer,Synthesis,有一个pythonsounddevice模块,它能够根据当前帧时间合成实时音频信号帧和块。rtd上的示例用法如下: 但是我想纯粹使用pygame中的功能来移植这个功能(可能使用pygame.mixer.Sound)。然而,看看文档,它看起来像是声音模块。我对这些几乎没有经验,也不知道如何开始。我能想到的最好的办法是: #!/usr/bin/env python3 import pygame as pg import numpy as np s_time = 0 def synth(frame
sounddevice
模块,它能够根据当前帧时间合成实时音频信号帧和块。rtd上的示例用法如下:
但是我想纯粹使用pygame中的功能来移植这个功能(可能使用pygame.mixer.Sound
)。然而,看看文档,它看起来像是声音
模块。我对这些几乎没有经验,也不知道如何开始。我能想到的最好的办法是:
#!/usr/bin/env python3
import pygame as pg
import numpy as np
s_time = 0
def synth(frames = 1024):
print("Buffer read")
global s_time
def frame(i):
# there are some magic numbers, sorry about that
return 0.2 * 32767 * np.sin(2.0 * np.pi * 440 * i / 48000)
arr = np.array([frame(x) for x in range(s_time, s_time + frames)]).astype(np.int16)
print(arr)
print(len(arr))
s_time = s_time + frames
return arr
running = True
pg.init()
pg.display.set_mode([320, 200])
pg.mixer.init(48000, -16, 1, 1024)
snd = pg.mixer.Sound(buffer=synth())
snd.play(-1)
while running:
events = pg.event.get()
for event in events:
if event.type == pg.KEYDOWN:
if event.key == pg.K_q:
print("Key pressed")
if event.key == pg.K_ESCAPE:
print("Quitting")
running = False
if event.type == pg.KEYUP:
if event.key == pg.K_q:
print("Key depressed")
但这只是循环前1024帧,而不是实时生成它们的正弦波形
有没有一种纯粹的pygame方式来进行实时声音合成,或者我必须放弃使用
souddevice
库?还有pysndfile
,也许你可以创建一个IO缓冲区(内存中),并打包数据以便pygame重新打开。不过,所有这些保存/加载都有点费劲。如果我需要求助于另一个库,我将只使用sounddevice和pygame。为了提高效率,我只想用pygame来完成这一切。