Last active
September 24, 2018 18:44
-
-
Save LevitatingBusinessMan/b48a5d6aabf333c492780efbeb8fbcdf to your computer and use it in GitHub Desktop.
Audio visualizer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/p5.js"></script> | |
<script src=" https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/addons/p5.sound.js"></script> | |
<style>body{margin:0px}</style> | |
<script> | |
let mic, | |
particles =[], | |
fft, | |
canvas, | |
circle = 3, | |
amp=0.2, | |
speed; | |
function preload(){ | |
sound = loadSound('song.mp3'); | |
} | |
function setup(){ | |
canvas = createCanvas(windowWidth,windowHeight); | |
canvas.mouseClicked(togglePlay); | |
fft = new p5.FFT(); | |
sound.amp(amp); | |
angleMode(DEGREES); | |
setInterval(() => { | |
if (sound.isPlaying()) | |
for (i=0;i < particles.length;i++) | |
particles[i].z += speed/3000; | |
}, 10) | |
} | |
function draw(){ | |
background(0); | |
translate(canvas.width/2, canvas.height/2); | |
fill(255); | |
stroke(255); | |
while(particles.length < 800) | |
particles.push({ | |
x:random(-width/2, width/2), | |
y:random(-height/2, height/2), | |
z:1 | |
}); | |
for (i=0;i < particles.length;i++) { | |
if(particles[i].x * particles[i].z > width || | |
particles[i].x * particles[i].z < -width || | |
particles[i].y * particles[i].z > height || | |
particles[i].y * particles[i].z < -height) | |
particles.splice(i,1); | |
else { | |
let x = particles[i].x; | |
let y = particles[i].y; | |
let z = particles[i].z; | |
if (sound.isPlaying()) line( | |
x/z/4 + x * z, | |
y/z/4 + y * z, | |
x * z, | |
y * z); | |
point(x*z , y*z); | |
} | |
} | |
let spectrum = fft.analyze(); | |
spectrum.splice(spectrum.length-250,250);//Remove the highest frequencies | |
speed = fft.getEnergy("bass"); | |
let bcircle = speed*(circle/10); | |
push(); | |
for (i=0;i < spectrum.length;i++) { | |
line(0,bcircle,0,bcircle + spectrum[i] /2); | |
rotate(180/spectrum.length); | |
} | |
pop(); | |
for (i=0;i < spectrum.length;i++) { | |
line(0,bcircle,0,bcircle + spectrum[i] /2); | |
rotate(-(180/spectrum.length)); | |
} | |
//let waveform = fft.waveform(); | |
} | |
// fade sound if mouse is over canvas | |
function togglePlay() { | |
if (sound.isPlaying()) { | |
sound.pause(); | |
} else { | |
sound.loop(); | |
} | |
} | |
function windowResized() { | |
resizeCanvas(windowWidth, windowHeight); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment