Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save ja-k-e/3a02b0c66e3e1c80c255 to your computer and use it in GitHub Desktop.

Select an option

Save ja-k-e/3a02b0c66e3e1c80c255 to your computer and use it in GitHub Desktop.
SVG Audio Visualizer 4: Ellipse Amoeba Swag
<input id=audiofile type=file>
<svg id=svg></svg>
// AudioContext and analyser integration from Ali Görkem's
// Pen "Audio Visualizer #3"
// http://codepen.io/agorkem/pen/PwyNOg/
// thanks dewd!
window.onload = function() {
var audio,
analyser,
audioContext,
sourceNode,
stream;
var svg = document.getElementById('svg'),
svgNS = svg.namespaceURI,
ellipse = document.createElementNS(svgNS, "ellipse"),
points = [];
var width = window.innerWidth,
height = window.innerHeight,
maxHeight = height * 0.5,
fftSize = 512, // 512
c = 0;
var audioInput = document.getElementById('audiofile');
// choose file
audioInput.addEventListener('change', function(event) {
stream = URL.createObjectURL(event.target.files[0]);
audio = new Audio();
audio.src = stream;
setup();
});
function setup() {
audio.addEventListener('canplay', function () {
document.body.className+='loaded';
var AudioContext = window.AudioContext || window.webkitAudioContext;
audioContext = new AudioContext();
analyser = (analyser || audioContext.createAnalyser());
analyser.minDecibels = -90;
analyser.maxDecibels = -10;
analyser.smoothingTimeConstant = 1;//0.75;
analyser.fftSize = fftSize;
sourceNode = audioContext.createMediaElementSource(audio);
sourceNode.connect(analyser);
sourceNode.connect(audioContext.destination);
audio.play();
update();
});
}
svg.setAttribute("width", width+"px");
svg.setAttribute("height", height+"px");
svg.setAttribute("viewBox", (width/-2) + " " + (height/-2) + " " + width + " " + height);
//ellipse.setAttribute("transform", "rotate(90 "+width/2+" "+height/2+")");
svg.appendChild(ellipse);
function update() {
var freqArray = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteTimeDomainData(freqArray);
// clear coords
var rx = 0, ry = 0;
var average = 0;
// for each frequency
for (var i = 0; i < freqArray.length; i++) {
average += freqArray[i];
}
average /= freqArray.length;
var avgRatio = (average - 100) / (255 - 100);
rx = avgRatio * (width / 2);
ry = avgRatio * (width / 2);
ellipse.setAttribute("rx", rx);
ellipse.setAttribute("ry", ry);
ellipse.setAttribute("fill", "hsl(" + c + ",100%," + (avgRatio * 60 + 10) + "%)");
c += 0.5;
requestAnimationFrame(update);
}
};
body {
margin: 0;
background-color: #000000;
font-family: 'Helvetica', sans-serif;
color: #FFFFFF;
}
input {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%);
z-index: 2;
}
body.loaded input {
display: none;
}
#svg {
display: block;
position: absolute;
top: 50%; left: 50%;
transform: translate3d(-50%, -50%, 0);
polygon {
stroke: none;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment