xxxxxxxxxx
96
let song;
let slider;
let particles = [];
//inorder the p5js to make a wave form we weed to have the fft object
let fft;
//to load the song from the file
function preload() {
song = loadSound("Love Unlimited Orchestra - Love's Theme.mp3");
}
function setup() {
createCanvas(500, 500);
colorMode(HSB, 359, 100, 100, 100);
slider = createSlider(0, 1, 0.5, 0.01);
song.play();
/* FFT is an analysis algorithm that isolates individual audio frequencies within a waveform. https://p5js.org/reference/#/p5.FFT */
fft = new p5.FFT();
}
function draw() {
background(0);
stroke(255);
noFill();
song.setVolume(slider.value());
let wave = fft.waveform(); //Returns an array of amplitude values (between -1.0 and +1.0)
stroke(random(255), random(255), random(255));
fft.analyze();
amp = fft.getEnergy(20, 200); //Returns the amount of volume at a specific frequency, using which we could use to control the behaviour of particle and thier responsiveness
strokeWeight(2);
beginShape();
//to built the waveform so we use the applitudes and that we got before and then use this to make the wave
for (let i = 0; i <= width; i++) {
let index = floor(map(i, 0, width, 0, wave.length / 2));
let x = i;
let y = wave[index] * 100 + height / 2;
vertex(x, y);
}
endShape();
let p = new Particle(2);
particles.push(p);
//creates the particle around the wave form
for (let i = 0; i < particles.length; i++) {
if (!particles[i].edge()) {
particles[i].move(amp > 100);
particles[i].show();
} else {
particles.splice(i, 1); //if the particle is out of the space then delete it from the array
}
}
}
function mouseClicked() {
if (song.isPlaying()) {
song.pause();
noLoop();
} else {
song.play();
loop();
}
}
//class for the particle
class Particle {
constructor(r) {
this.x = random(0, width);
this.y = height / 2;
this.r = r;
}
move(cond) {
this.y += random(-10, 10);
if (cond) {
this.y += random(-20, 20);
}
}
edge() {
if (this.y < 0 || this.y > height) {
return true;
} else {
return false;
}
}
show() {
noStroke();
fill(255);
ellipse(this.x, this.y, this.r);
}
}