xxxxxxxxxx
76
/* visualize sound
1. load the sound
2. analyze sound
3. map the sound data to our shapes
*/
let sound;
let amp, fft;
let level, spectrum;
function preload() {
//step1 to load the sound
sound = loadSound('assets/MOTK.mp4')
}
function setup() {
createCanvas(windowWidth, windowHeight);
sound.loop(); //to play and loop the sound
amp = new p5.Amplitude();
fft = new p5.FFT();
rectMode(CENTER);
}
function draw() {
//update the values
level = amp.getLevel();
spectrum = fft.analyze();
background('black');
let time = frameCount /60;
if(time <5){
spec();
}else if(time<10){
event2();
}else if(time<15){
event1();
}
}
function event1() {
fill(random(255));
let size = map(level,0,1,5,50);
let colNum = 10;
let rowNum =5;
let colGap = width/colNum;
let rowGap = height/rowNum;
for(let row = 0; row<rowNum;row++){
for(let col = 0; col<colNum;col++){
rect(col*colGap,row*rowGap, size, size);
}
}
}
function event2() {
stroke('white');
fill('white');
let x1 = 0;
let y1 = width/2;
let x2 = map(level, 0,1,width/2,width);
let y2 =y1;
let size = map(level,0,1,0,20);
line(x1,y1, x2,y2);
circle(x2,y2,size);
}
function spec() {
for (let i = 0; i< spectrum.length; i+=10){
let x = map(i, 0, spectrum.length, 0, width);
let y = map(spectrum[i],0,255,height/2,height);
fill(random(255));
stroke('white');
strokeWeight(3);
point(x,y);
strokeWeight(.4);
line(x,y,x,height);
}
}