Search code examples
javascriptaudiocanvasvisualizer

Audio Visualizer with Canvas


I'm building an audio visualizer based on a few different codepen experiments I found. I'm new to canvas, and am trying to figure out how to make this run a little more smoothly. So far, it's working pretty well: http://codepen.io/ericjacksonwood/pen/bBGEbM

This is the structure of the visualizer itself:

function Visualizer() {
  canvasContext.clearRect(0, 0, canvas.width, canvas.height);
  analyser.getByteFrequencyData(frequencyData);

  var frequencyWidth = (canvas.width / bufferLength * 4),
    frequencyHeight = 0,
    x = 0;

  for (var increment = 0; increment < bufferLength; increment++) {
    frequencyHeight = frequencyData[increment] * (canvas.height * 0.002);

  canvasContext.fillStyle = "#0000FF";
  canvasContext.fillRect(x, canvas.height - frequencyHeight, frequencyWidth, frequencyHeight);
    x += frequencyWidth + 2;
  }

  call = requestAnimationFrame(Visualizer);
}

However, I'd like the bars to fall to the bottom when paused, and not just have them disappear completely. Here's a better example of the functionality I'm looking to achieve: http://codepen.io/ericjacksonwood/pen/xRmXEy

This example works well, but I don't need rainbow bars, so I feel like the majority of the JS can be ignored.


Solution

  • The bars are disappearing completely because you are stopping the animations. Just pause the audio and let the animation render nothing. Comment out cancelAnimationFrame(call); and you should see what you want. I tested your code by commenting the line, and experienced what you would like.