setup()
setup() runs once when the sketch starts. It is where you initialize your canvas, audio system, and draw any static instructions. Notice that mic.start() is NOT called here - it waits for user interaction (a click or tap) because modern browsers require user gesture to access the microphone for security reasons.
function setup() {
createCanvas(windowWidth, windowHeight);
// Tip: Use windowWidth/windowHeight for responsive canvas
// Initialize audio input and FFT analyzer
mic = new p5.AudioIn(); // Create an audio input object
// mic.start() is called later on user gesture for mobile compatibility
fft = new p5.FFT(); // Create an FFT analyzer
fft.setInput(mic); // Connect the FFT analyzer to the microphone input
// Set up text for instructions
textAlign(CENTER, CENTER); // Align text to the center
textSize(18); // Set font size
fill(255); // Set text color to white
noStroke(); // No border for the text
// Initially draw the instruction message
background(0); // Black background
text("Tap or click anywhere to start audio and watch the shapes dance!", width / 2, height / 2);
}
Line-by-line explanation (6 lines)
🔧 Subcomponents:
createCanvas(windowWidth, windowHeight);
Creates a canvas that fills the entire browser window and responds to resizing
mic = new p5.AudioIn();
fft = new p5.FFT();
fft.setInput(mic);
Initializes the microphone input and FFT analyzer, then connects them so the analyzer can examine the microphone audio
textAlign(CENTER, CENTER);
textSize(18);
fill(255);
noStroke();
Configures text to be centered and white before drawing the instruction message
createCanvas(windowWidth, windowHeight);- Creates a canvas that spans the full width and height of the browser window, making the visualization fullscreen and responsive
mic = new p5.AudioIn();- Creates a new microphone input object that will capture audio from your device - mic.start() is delayed until the user clicks for mobile compatibility
fft = new p5.FFT();- Creates a Fast Fourier Transform analyzer object that will break the audio signal into frequency bands we can analyze
fft.setInput(mic);- Tells the FFT analyzer to analyze the microphone's audio stream instead of the default speakers
textAlign(CENTER, CENTER);- Sets text alignment so the text() function centers its output at the x,y coordinates you provide
text("Tap or click anywhere to start audio and watch the shapes dance!", width / 2, height / 2);- Draws the instruction message centered on the canvas at the middle point (width/2, height/2)