Playing synthesized audio real time without reading or writing wav-files or arrays

Viewed 303

Is it possible in python to play audio by writing directly to the audio output, without making or reading a wav-file or making an array to be played.

I'v been working on a synth project and I would like to synthesise and modulate sound realtime. I'm currently programming using mac, but the final software would be on a raspberry pi. With an arduino a was able to do this by using a 8-bit R2R-ladder as DAC and writing directly to GPIO pins composing the DAC. Here is a small simplified code for making "white" noise on arduino:

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

Another example on making a nice 8-bit kick drum. I would like to calculate the sine wave on the fly, but arduino was too slow to do it:

    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;

Would something like this be possible with python running on a laptop or a raspberry pi?

1 Answers

On a laptop, this can be done with PyAudio - Portaudio bindings for python.

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()
Related