Skip to content

Instantly share code, notes, and snippets.

@alexmacy
Last active June 29, 2017 22:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexmacy/778cd868df8168b9c088d075aab6216e to your computer and use it in GitHub Desktop.
Save alexmacy/778cd868df8168b9c088d075aab6216e to your computer and use it in GitHub Desktop.
Horizontal Ellipses
license: mit

This listens to your computer's microphone and draws the contents of the audio buffer as a series of (mostly) horizontal ellipses.

This was made as part of a series exploring the visualization of audio that was presented at a d3.oakland. A big list of the demos from this series can be found here.

<!DOCTYPE html>
<title>Horizontal Ellipses</title>
<body style="margin: 0px">
<canvas></canvas>
</body>
<script>
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const analyser = audioCtx.createAnalyser();
const canvas = document.querySelector('canvas');
canvas.setAttribute('width',innerWidth);
canvas.setAttribute('height',innerHeight);
const canvasCtx = canvas.getContext("2d");
canvasCtx.fillStyle = 'rgb(0, 0, 0)';
canvasCtx.strokeStyle = 'rgb(255, 0, 0)';
canvasCtx.lineWidth = .1;
const dataArray = new Uint8Array(analyser.frequencyBinCount);
navigator.getUserMedia (
{audio: true},
function(stream) {
audioCtx.createMediaStreamSource(stream).connect(analyser);
draw();
},
function(err) {
console.log('The following gUM error occured: ' + err);
}
);
function draw() {
canvasCtx.fillRect(0, 0, canvas.width, canvas.height);
analyser.getByteTimeDomainData(dataArray);
const [min, max] = [Math.min(...dataArray), Math.max(...dataArray)];
if (max - min > 2) {
for(let i = 0; i < dataArray.length; i++) {
const thisVol = ((dataArray[i] - min)/(max-min)) * Math.min(innerWidth, innerHeight)/2;
const thisRotation = i/dataArray.length * Math.PI
const x = thisVol * Math.cos(thisRotation);
const y = thisVol * Math.sin(thisRotation);
canvasCtx.beginPath();
canvasCtx.ellipse(
canvas.width/2,
canvas.height/2,
Math.abs(x),
Math.abs(y),
thisRotation,
0,
2 * Math.PI
);
canvasCtx.stroke();
}
}
requestAnimationFrame(draw);
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment