Home JS visualization increases volume for each new audio file
Reply: 0

JS visualization increases volume for each new audio file

staniel
1#
staniel Published in 2018-02-11 15:18:04Z

I have an audio visualization function:

function visualize() {
  audio = document.getElementById('audio');
  audio.crossOrigin = 'anonymous'
  var context = new AudioContext();
  var src = context.createMediaElementSource(audio);
  var analyser = context.createAnalyser();
  var canvas = document.getElementById('canvas');
  canvas.width = 223;
  canvas.height = 55;
  var ctx = canvas.getContext('2d');
  src.connect(analyser);
  analyser.connect(context.destination);
  analyser.fftSize = 256;
  var bufferLength = analyser.frequencyBinCount;
  var dataArray = new Uint8Array(bufferLength);
  var WIDTH = canvas.width;
  var HEIGHT = canvas.height;
  var barWidth = WIDTH / bufferLength;
  var barHeight;
  var x = 0;

  function renderFrame() {
    requestAnimationFrame(renderFrame);
    x = 0;
    analyser.getByteFrequencyData(dataArray);
    ctx.fillStyle = 'rgba(38, 26, 51, 0.7)';
    ctx.fillRect(0, 0, WIDTH, HEIGHT);
    for (var i = 0; i < bufferLength; i++) {
      barHeight = dataArray[i]*0.2;
      ctx.fillStyle = '#392d50';
      ctx.fillRect(x, HEIGHT - barHeight, barWidth, barHeight);
      x += barWidth + 1;
    }
  }
  renderFrame();
};

When it is called on the first audio file, the volume level is normal, but when it is called on the next file, it increases audio volume level, and also for the next one after this and so on - volume level is just growing up. How can I modify this function to keep volume level the same for each new audio playing?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.296735 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO