我目前正在尝试使用pygame.mixer
或sounddevice
编写一个python合成器,以输出我在numpy array
中创建的正弦波样本。在创建正弦波之前,必须说明波形的持续时间,例如:sin(frequency * 2 * Pi * duration)
因此,你如何在用户按键的持续时间内播放此声音。
当我阅读时,没有太多关于python的文章看起来很容易理解,因此任何帮助都将受到赞赏。
另外,如果有人能解释或给予一个使用python缓冲区对象的sounddevice.Stream
或sounddevice.RawStream
如何工作的例子,如果它对我的情况有帮助,那将非常感谢。
我已经尝试过使用sounddevice.play()
,但这似乎是我试图实现的基本功能。我也试过创建一小段正弦波,并循环它的用户输入,但这不会工作,当我来调制的声音。
我不喜欢使用sounddevice.play()
的另一个原因是因为你需要延迟程序,因为我已经使用了sounddevice.wait()
,如果不是程序运行到最后没有播放任何东西。
在观看这段视频时…https://www.youtube.com/watch?v=tgamhuQnOkM ...它使用c++
来编程一个synth,他使用了一个单独的模块,我认为它运行一个后台线程,但他的模块单独获取每个样本,而不是作为一个数组。
我也试过使用pygame.sndarray.make_sound()
。这是一个例子,当/如果synth工作时,我想做的事情:
import numpy as np # download
import sounddevice as sd # download
import time
stream = []
# Main Controls
sps = 44100 # DON'T CHANGE
carrier_hz = 440.0
duration_s = 1.0
atten = 0.3
def amplitudeMod(t_samples, carrier):
# Modulate the amplitude of the carrier
ac = 0.2 # amplitude 0 = min, 1 = max
ka = 1.0 # range of change 0.1 = less, 1.0 = most
modulator_hz = 0.0 # frequency of modulation 20hz max
modulator = np.sin(2 * np.pi * modulator_hz * t_samples / sps)
envelope = ac * (1.0 + ka * modulator)
return carrier * envelope
def frequencyMod(t_samples, sps):
# Modulate the frequency of the carrier
k = 50.0 # range of change 0.1 = less, ?? = most
modulator_hz = 10.0 # frequency of modulation
carrier2 = 2 * np.pi * t_samples * carrier_hz / sps
modulator = k * np.sin(2 * np.pi * t_samples * modulator_hz / sps)
return np.cos(carrier2 + modulator)
# Create carrier wave
t_samples = np.arange(duration_s * sps)
carrier = np.sin(2 * np.pi * carrier_hz * t_samples / sps)
choice = input("1) Play sine\n2) Play amplitude modulation\n3) Play frequency modulation\n;")
if choice == "1":
output = carrier
if choice == "2":
output = amplitudeMod(t_samples, carrier)
if choice == "3":
output = frequencyMod(t_samples, sps)
# Output
output *= atten
sd.play(output, sps)
sd.wait()
sd.stop()
有没有办法把它创建成一个pygame按键事件,它只在按键被按下时播放正弦波,然后在按键被释放时停止。
1条答案
按热度按时间ttisahbt1#
在尝试了几个库(包括pygame,它似乎不容易支持动态生成和更改音频流)之后,我能够使用Python sounddevice库制作一个可控的音调生成器。我正在运行MacOS Monterey(Intel)和Python 3.11。