Sound visualization 101 – P5js

Just messing about a little bit with the sound object in P5js. Its a simple visualization of the amplitude of the song mapped to the radius of a circle. Wait for song to load.


var song;
var multiplier = 3.5;
var volhistory = [];
var amp;
var button;
function setColor(){
//color
var colorvar = frameCount;
if (colorvar >= 255) {
colorvar = 0;
} else {
colorvar = frameCount;
}
var rC = map(colorvar, 0, width, random(255), 255);
var g = map(colorvar, 0, width, random(255), 100);
var b = map(colorvar, 0, height, random(255), 255);
stroke(rC, g, b, 80);
}
function toggleSong(){
if (song.isPlaying()){
song.pause();
}
else{
song.play();
}
}
function preload(){
song = loadSound('file.mp3')
}
function setup() {
background (0);
createCanvas(600, 600);
angleMode(DEGREES);
button = createButton("toggle");
button.mousePressed(toggleSong);
song.play();
amp = new p5.Amplitude();
}
function draw() {
// background(0);
push();
// var volume = 1;
var volume = amp.getLevel()*multiplier;
volhistory.push(volume);
setColor();
noFill();
translate(width/2, height/2);
beginShape();
//strokeWeight(2);
for(var i =0; i<360;i++){ var r = map(volhistory[i],0,1,10,300); var x = r*cos(i); var y = r*sin(i); // point(i,y); vertex(x,y); } endShape(); //ellipse(width/2,height/2,200, 200*volume) //bounds if(volhistory.length>360){
volhistory.splice(0,1);
}
if (frameCount % 300 === 0) {
background(0);
}
}