setup()
setup() runs once when the sketch starts. It's the right place to request microphone permission, configure audio analysis tools, and populate arrays of objects before the animation loop begins.
function setup() {
createCanvas(windowWidth, windowHeight);
// Click to start audio - this is crucial for web audio to work
userStartAudio();
mic = new p5.AudioIn();
mic.start();
fft = new p5.FFT();
fft.setInput(mic);
colorMode(HSB, 360, 100, 100, 100);
// Initialize cars with random positions and a unique ID
for (let i = 0; i < NUM_CARS; i++) {
cars.push(new Car(random(width), random(height), i));
}
}
Line-by-line explanation (9 lines)
π§ Subcomponents:
for (let i = 0; i < NUM_CARS; i++) {
Creates NUM_CARS Car objects at random positions and adds them to the cars array
createCanvas(windowWidth, windowHeight);- Makes the canvas fill the entire browser window.
userStartAudio();- Tells the browser it's okay to start the audio context - browsers require this to be tied to user interaction for audio to actually play or be captured.
mic = new p5.AudioIn();- Creates an audio input object representing the user's microphone.
mic.start();- Requests microphone access from the browser and begins capturing audio.
fft = new p5.FFT();- Creates a Fast Fourier Transform analyzer, which breaks incoming sound into its frequency components.
fft.setInput(mic);- Tells the FFT analyzer to analyze the microphone's audio stream rather than the default master output.
colorMode(HSB, 360, 100, 100, 100);- Switches color values from default RGB to Hue-Saturation-Brightness with a 0-360 hue range and 0-100 ranges for saturation, brightness, and alpha - handy for rainbow color cycling.
for (let i = 0; i < NUM_CARS; i++) {- Loops NUM_CARS times to create that many Car objects.
cars.push(new Car(random(width), random(height), i));- Creates a new Car at a random position on screen, tagged with a unique id, and adds it to the cars array.