diff --git a/src/index.js b/src/index.js index e3da635..3544e8a 100644 --- a/src/index.js +++ b/src/index.js @@ -1,9 +1,16 @@ import p5 from 'p5'; - +import 'p5/lib/addons/p5.sound'; import './index.scss'; -function getRandomColorValue() { - return Math.floor(Math.random() * 256); +const VOLUME_NORMALIZATION = 1000; +const THRESHOLD = 10 / VOLUME_NORMALIZATION; + +function getColorValue(volume) { + return Math.floor(volume * VOLUME_NORMALIZATION * 256); +} + +function getWidth(volume) { + return volume * VOLUME_NORMALIZATION; } function getRandomX() { @@ -14,14 +21,47 @@ function getRandomY() { return Math.floor(Math.random() * window.innerHeight); } -const instance = new p5(( sketch ) => { - sketch.setup = () => { - sketch.createCanvas(window.innerWidth, window.innerHeight); - }; - sketch.draw = () => { - sketch.background(0); - sketch.fill(getRandomColorValue()); - sketch.rect(getRandomX(),getRandomY(),50,50); - }; -}); +async function main() { + const mic = new p5.AudioIn(); + mic.start(); + + const instance = new p5(( sketch ) => { + sketch.setup = () => { + sketch.createCanvas(window.innerWidth, window.innerHeight); + }; + + function drawBar(bar) { + sketch.fill(getColorValue(bar.volume)); + sketch.rect(bar.x, 0, getWidth(bar.volume), window.innerHeight); + } + + let bars = []; + + sketch.draw = () => { + sketch.background(0); + + const volume = mic.getLevel(); + const x = getRandomX(); + bars.push({ + volume, + // pitch, + x, + }); + + const newBars = []; + for (const bar of bars) { + bar.volume = bar.volume / 1.5; + if (bar.volume <= THRESHOLD) { + continue; + } + drawBar(bar); + newBars.push(bar); + }; + + bars = newBars; + }; + }); +} + +main(); diff --git a/src/index.scss b/src/index.scss index 4221350..5548e4b 100644 --- a/src/index.scss +++ b/src/index.scss @@ -1,4 +1,5 @@ body { margin: 0; overflow: hidden; + transform: rotateY(180deg); }