4

是否可以在 python 中通过直接写入音频输出来播放音频,而无需制作或读取 wav 文件或制作要播放的数组。

我一直在做一个合成器项目,我想实时合成和调制声音。我目前正在使用 mac 进行编程,但最终的软件将在树莓派上。使用 arduino,a 能够通过使用 8 位 R2R 梯形图作为 DAC 并直接写入组成 DAC 的 GPIO 引脚来做到这一点。这是一个用于在 arduino 上制造“白”噪声的小简化代码:

    for (int t=0;t<1000;t++){
    PORTD = random(0,255);  //PORTD is the DAC output
    delayMicroseconds(10);
    }

另一个制作漂亮的 8 位底鼓的例子。我想即时计算正弦波,但 arduino 太慢了,无法做到:

    while(n < 200){
    for (int t=0;t<100;t++){
        PORTD = sine[t]/2; //sine[] is a previously defined array containing a sine wave
        delayMicroseconds(n);
        }
    n = n + 15;

在笔记本电脑或树莓派上运行 python 会不会发生这样的事情?

4

1 回答 1

1

在笔记本电脑上,这可以通过 PyAudio - Python 的 Portaudio 绑定来完成。

import pyaudio
from math import pi
import numpy as np

p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paFloat32, channels=1, rate=44100, output=1,)


def make_sinewave(frequency, length, sample_rate=44100):
    length = int(length * sample_rate)
    factor = float(frequency) * (pi * 2) / sample_rate
    waveform = np.sin(np.arange(length) * factor)

    return waveform

wave = make_sinewave(500, 1)

stream.write(wave.astype(np.float32).tostring())
stream.stop_stream()
stream.close()
于 2020-05-09T06:30:34.133 回答