xxxxxxxxxx
44
// This program displays an animated visualization of the music playing.
// It uses an amplitude object to measure the sound level, and then uses
// the level to determine the size of the shape in the visualization.
let amp, sound, cnv, r;
let volHistory = [];
function preload() {
sound = loadSound("music.mp3"); // Loads the music file
}
function setup() {
cnv = createCanvas(windowWidth, windowHeight); // Creates the canvas
cnv.mouseClicked(togglePlay); // Creates an event listener to toggle the sound
angleMode(DEGREES); // Change the mode to DEGREES
amp = new p5.Amplitude(); // Creates a new amplitude object
colorMode(HSB);
}
function draw() {
background(0);
stroke(255);
fill(frameCount%360, 100, 100);
volHistory.push(amp.getLevel()); // Adds the current sound level to the volHistory array
translate(mouseX, mouseY); // Centers the position of the shape
beginShape(); // Starts the shape
for (let i = 0; i < volHistory.length; i++) {
r = map(volHistory[i], 0, 1, 0, width*2); // Maps the sound level to a size
vertex(r * sin(i), r * cos(i)); // Sets the vertex
}
endShape(); // Ends the shape
if (volHistory.length > 360) {
volHistory.splice(0, 1); // Remove the first item
}
}
function togglePlay() {
sound.isPlaying() ? sound.pause() : sound.loop(); // If the sound is playing, pause it. Otherwise, loop it.
}