Created
October 18, 2017 05:09
-
-
Save dudo/7be91b7fa2e1fcc7db39d99e20e1ea5f to your computer and use it in GitHub Desktop.
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
const audio = new AudioContext(), | |
sound = audio.createMediaStreamSource(stream), | |
analyser = audio.createAnalyser(); | |
analyser.minDecibels = -60; | |
// microphone -> filter -> destination. | |
sound.connect(analyser); | |
analyser.connect(audio.destination); | |
const frequencyData = new Uint8Array(analyser.frequencyBinCount).slice(0, 32), | |
spectrum = document.querySelector('#spectrum'); | |
const frequencies = frequencyData.map((_, i) => { | |
spectrum.appendChild(document.createElement('DIV')); | |
return i * audio.sampleRate/analyser.fftSize | |
}) | |
const bars = document.querySelectorAll("#spectrum > div"); | |
let avg = 0; | |
function renderFrame() { | |
requestAnimationFrame(renderFrame); | |
// update data in frequencyData | |
analyser.getByteFrequencyData(frequencyData); | |
// render frame based on values in frequencyData | |
let sums = 0, total = 0.001; | |
frequencyData.forEach((fd, i) => { | |
bars[i].style.height = fd + "px"; | |
sums += fd * frequencies[i]; | |
total += fd; | |
bars[i].style.backgroundColor = "hsl(" + ~~avg + ",60%,70%)"; | |
}) | |
avg = sums / total; | |
} | |
renderFrame(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment