Skip to content

Sound with p5 ​

Basthon's p5 module can now make sound, in isolated kernels as with the legacy kernel: p5.sound is loaded with p5.js. You can play sound files (loadSound), synthesize notes (Oscillator, MonoSynth, Envelope…) and analyse what you hear (FFT, Amplitude). The classes of p5.sound are used directly after from p5 import *.

First try, a theremin: hold the click on the drawing, the mouse sets the pitch and the volume of the sound, and an FFT draws its spectrum and its waveform.

python
from p5 import *

osc = None
fft = None

def setup():
    global osc, fft
    createCanvas(500, 300)
    osc = Oscillator("triangle")
    osc.amp(0)
    osc.start()
    fft = FFT()

def draw():
    background(30)
    if mouseIsPressed:
        osc.freq(map(mouseX, 0, width, 100, 1000), 0.05)
        osc.amp(map(mouseY, 0, height, 0.5, 0, True), 0.05)
    else:
        osc.amp(0, 0.2)
    # the spectrum (up to about 5 kHz)
    spectrum = list(fft.analyze())[:200]
    noStroke()
    fill(255, 200, 0)
    w = width / len(spectrum)
    for i, value in enumerate(spectrum):
        h = map(value, 0, 255, 0, height)
        rect(i * w, height - h, w, h)

run()

Play with it!

Sound files can be those of the program (opened or added as extra files), or even made by Python. The example notebook computes the samples of a chord with the wave module, plays it with loadSound, and finds its three notes in the spectrum. It ends with a little piano played with the mouse or the keyboard.

Open the notebook

Sound stops when the drawing is replaced by another one or when the kernel restarts. As for any web page, the browser only allows sound after an action of the user: clicking "Run" is usually enough, otherwise userStartAudio() in a click handler does the trick.

The microphone (AudioIn) and playing videos (createVideo) are still reserved to the legacy kernel for now.