2

我目前正在尝试使用pygame.mixersounddevice输出我在numpy array. 例如,在创建正弦波之前必须说明波形的持续时间:sin(frequency * 2 * Pi * duration)因此,您如何在用户按键的持续时间内播放此声音。

当我阅读似乎很容易理解的python时,关于python的文章并不多,因此我们将不胜感激。

此外,如果有人可以解释或举例说明sounddevice.Streamsounddevice.RawStream使用 python 缓冲区对象的工作原理,以及它是否对我的情况有所帮助,那将不胜感激。

我已经尝试过使用sounddevice.play(),但这对于我想要实现的目标来说似乎非常基本。我也尝试过创建一小段正弦波并将其循环以供用户输入,但是当我要调制该声音时,这将不起作用。

我不喜欢使用的另一个原因sounddevice.play()是因为您需要延迟程序,就像我使用sounddevice.wait()的那样,好像程序运行到最后而不播放任何东西一样。

观看此视频时 ... https://www.youtube.com/watch?v=tgamhuQnOkM ... 用于c++对合成器进行编程,他使用了一个单独的模块,我认为该模块运行后台线程,但他的模块分别获取每个样本而不是作为一个数组。

我也尝试过使用pygame.sndarray.make_sound(). 这是当/如果合成器工作时我想做的事情的一个例子:

            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 键事件,仅在按下键时播放正弦波,然后在释放键时停止。

4

0 回答 0