Last active
August 29, 2015 14:01
-
-
Save DavidReinberger/f8c8b1687bc34c02fd24 to your computer and use it in GitHub Desktop.
Bars Visualization
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
window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext; | |
window.onload = function () { | |
var canvas = document.getElementById('c'), //initialize for Canvas | |
c = canvas.getContext('2d'), | |
cw = canvas.width, | |
ch = canvas.height, //get height and width | |
audiosource = document.getElementById('audio'), | |
lenght = audiosource.duration * 30, //we need the audio duration to know for how long the animation should be captured - 30 FPS | |
ticker = 0, //frame identifier | |
bar = [], //animations | |
clrs; //colors | |
audiosource.play(); | |
var context = new webkitAudioContext(), | |
source = context.createMediaElementSource(audiosource), | |
analyser = context.createAnalyser(), | |
twopit = 2 * Math.PI, | |
centerw = cw / 2, | |
centerh = ch / 2, | |
radius = 300; | |
source.connect(analyser); | |
analyser.connect(context.destination); | |
var frequencyData = new Uint8Array(analyser.frequencyBinCount); | |
analyser.getByteFrequencyData(frequencyData); | |
analyser.fftSize = 512; | |
for (var a = 0; a < analyser.fftSize / 2; a++) { | |
d = a / 40.7436654315; | |
bar.push({ | |
w: 2, | |
x: centerw + (radius * Math.cos(d)), //left/right | |
y: centerh + (radius * Math.sin(d)), //up/down | |
rot: (a * 1.40625) * (Math.PI / 180) | |
}) | |
}; | |
function visualize() { | |
requestAnimationFrame(visualize); | |
analyser.getByteFrequencyData(frequencyData); | |
var cx, | |
cy; | |
for (var i = 0; i < analyser.fftSize / 2; i++) { | |
cx = bar[i].x + 0.5 * ((frequencyData[i] / 512) * 100); | |
cy = bar[i].y + 0.5 * bar[i].w; | |
c.translate(cx, cy); | |
c.rotate(bar[i].rot); | |
c.translate(-cx, -cy); | |
c.fillRect(bar[i].x, bar[i].y, bar[i].w, -(frequencyData[i] / 512) * 100); | |
c.clearRect(bar[i].x, bar[i].y - (frequencyData[i] / 512) * 100, bar[i].w + 3, -(frequencyData[i] / 512) * 100); | |
}; | |
}; | |
visualize(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment