setup()
setup() runs once when the sketch starts. Here it initializes the canvas, switches to HSB color mode for easier rainbow painting, and sets up the entire p5.sound pipeline: microphone → FFT analyzer. Understanding this initialization order is crucial for audio sketches.
function setup() {
createCanvas(windowWidth, windowHeight);
colorMode(HSB, 360, 100, 100); // Set color mode to HSB for rainbow
mic = new p5.AudioIn(); // Create an audio input object
mic.start(); // Start listening to the microphone
fft = new p5.FFT(); // Create an FFT object to analyze frequencies
fft.setInput(mic); // Connect FFT to the microphone
userStartAudio(); // Prompt the user for microphone access. This is essential!
}
Line-by-line explanation (7 lines)
createCanvas(windowWidth, windowHeight);- Creates a canvas that fills the entire browser window by using windowWidth and windowHeight variables.
colorMode(HSB, 360, 100, 100);- Switches from RGB to HSB color mode, where 360 is the hue range (0-360 degrees on the color wheel), and 100 is the saturation and brightness range—this makes rainbow colors much easier to create.
mic = new p5.AudioIn();- Creates a new p5.AudioIn object that will capture sound from your microphone and stores it in the 'mic' variable.
mic.start();- Tells the microphone object to start listening and recording audio input.
fft = new p5.FFT();- Creates a new Fast Fourier Transform analyzer that will break down audio into frequency bands.
fft.setInput(mic);- Connects the FFT analyzer to the microphone input so it analyzes your voice or sounds in real time.
userStartAudio();- Prompts the browser to request microphone permission from the user—this is required before p5.sound can access audio.