audio canvas fft

Using audio data to draw circles with canvas to screen

by Chris

HTML

<audio id='v' controls crossOrigin="anonymous" src="https://upload.wikimedia.org/wikipedia/en/3/3d/Sample_of_Daft_Punk%27s_Da_Funk.ogg" type="video/mp4"></audio><br />
<canvas width="512" height="256" id="c"></canvas>

JavaScript

window.context = new AudioContext();
video = context.createMediaElementSource(document.getElementById('v'));
analyser = context.createAnalyser(); //we create an analyser
analyser.smoothingTimeConstant = 0.9;
analyser.fftSize = 512; //the total samples are half the fft size.
video.connect(analyser);
analyser.connect(context.destination);
window.ctx = document.getElementById('c').getContext("2d");

function draw() {
  var array = new Uint8Array(analyser.fftSize);
  analyser.getByteTimeDomainData(array);
  ctx.clearRect(0, 0, 512, 512);

  var average = 0;
  var max = 0;
  for (i = 0; i < array.length; i++) {
    a = Math.abs(array[i] - 128);
    average += a;
    max = Math.max(max, a);
  }

  average /= array.length;
  ctx.fillStyle = 'blue';
  ctx.fillRect(0, 512-average, 512, 512);
  ctx.beginPath();
  ctx.arc(128, 128, average, 0, Math.PI * 2, true);
  ctx.arc(128 + 256, 128, max, 0, Math.PI * 2, true);
  ctx.font = "30px Arial";
  ctx.fillText("Average: "  + average, 10, 50);
  ctx.fillText("Max: "  + max, 10, 80);
  ctx.closePath();
  ctx.fill();

  requestAnimationFrame(draw);
}
draw();