xxxxxxxxxx
115
let r;
let angle = 0; //Rotation angle
let zoom = 1;
let song, fft, amp;
let playButton;
let bumpiness = 0.2;
let thetaValue = 6;
let phyValue = 5;
function preload() {
song = loadSound("music.mp3");
}
function setup() {
createCanvas(windowWidth, windowHeight, WEBGL);
angleMode(DEGREES);
colorMode(HSB);
strokeWeight(3);
noFill();
r = width / 3;
pixelDensity(3);
// analyse music
fft = new p5.FFT();
amp = new p5.Amplitude();
playButton = createButton("Play Music");
playButton.position(20, 20);
playButton.mousePressed(startAudio);
}
function draw() {
clear();
// Get music information
let spectrum = fft.analyze();
let bass = fft.getEnergy("bass");
let mid = fft.getEnergy("mid");
let treble = fft.getEnergy("treble");
let level = amp.getLevel();
// Change color based on frequency
let hue = map(bass, 0, 255, 0, 360);
let saturation = map(mid, 0, 255, 80, 100);
let brightness = map(treble, 0, 255, 80, 100);
stroke(hue, saturation, brightness);
//background color
let bgColor = map(level, 0, 1, 0, 255);
background(bgColor, bgColor, bgColor);
// Change shape based on frequency
bumpiness = map(bass, 0, 255, 0.2, 1.5);
thetaValue = map(mid, 0, 255, 4, 10);
phyValue = map(treble, 0, 255, 4, 10);
//Control the scaling size based on the amplitude
let zoom = map(level, 0, 1, 0.5, 2);
zoom = constrain(zoom, 0.2, 1.5);
scale(zoom);
//Rotate based on frequency
rotateX(angle * map(bass, 0, 255, 0.5, 2));
rotateY(angle * map(mid, 0, 255, 0.5, 2));
rotateZ(angle * map(treble, 0, 255, 0.5, 2));
//Draw shapes
if (level > 0.2) {
beginShape(POINTS);
for (let theta = 0; theta < 180; theta += 2) {
for (let phy = 0; phy < 360; phy += 2) {
let r_dynamic = r * (1 + bumpiness * tan(thetaValue * theta) * sin(phyValue * phy));
let x = r_dynamic * sin(theta) * cos(phy);
let y = r_dynamic * sin(theta) * sin(phy);
let z = r_dynamic * cos(theta);
vertex(x, y, z);
}
}
endShape();
} else {
beginShape();
for (let theta = 0; theta < 180; theta += 2) {
for (let phy = 0; phy < 360; phy += 2) {
let r_dynamic = r * (1 + bumpiness * sin(thetaValue * theta) * cos(phyValue * phy));
let x = r_dynamic * sin(theta) * cos(phy);
let y = r_dynamic * sin(theta) * sin(phy);
let z = r_dynamic * cos(theta);
vertex(x, y, z);
}
}
endShape();
}
angle += 0.8; // change the rotation angle
}
function startAudio() {
if (getAudioContext().state !== "running") {
getAudioContext().resume();
}
if (!song.isPlaying()) {
song.play();
playButton.html("Pause Music");
} else {
song.pause();
playButton.html("Play Music");
}
}