setup()
setup() runs once when the sketch starts. Here we initialize the canvas size, request microphone permission, and configure the audio analysis tools. The p5.sound library requires userStartAudio() to be called before mic input works—this is a browser security feature.
function setup() {
createCanvas(windowWidth, windowHeight);
// Click to start audio
userStartAudio();
mic = new p5.AudioIn();
mic.start();
fft = new p5.FFT();
fft.setInput(mic);
colorMode(HSB, 360, 100, 100, 100);
}
Line-by-line explanation (7 lines)
🔧 Subcomponents:
mic = new p5.AudioIn();
mic.start();
fft = new p5.FFT();
fft.setInput(mic);
Creates a microphone input object and an FFT analyzer that listens to the microphone stream
colorMode(HSB, 360, 100, 100, 100);
Sets color mode to Hue-Saturation-Brightness where hue ranges 0–360 (like a color wheel), making rainbow effects easy
createCanvas(windowWidth, windowHeight);- Creates a canvas that fills the entire browser window, using special variables that update if the window resizes
userStartAudio();- Pauses the sketch and waits for the user to click before starting audio input—this is required by web browsers for security
mic = new p5.AudioIn();- Creates a new microphone input object that will capture sound from the user's device
mic.start();- Starts listening to the microphone and collecting audio data
fft = new p5.FFT();- Creates a new FFT (Fast Fourier Transform) object that will break audio into separate frequency bands
fft.setInput(mic);- Tells the FFT analyzer to listen to the microphone input instead of other audio sources
colorMode(HSB, 360, 100, 100, 100);- Switches from RGB to HSB color mode: hue (0–360 like a rainbow wheel), saturation (0–100), brightness (0–100), alpha (0–100)