Search code examples
javascriptaudiohtml5-audioweb-audio-api

Exporting intensity of audio in Web Audio API


I'm trying to find the intensity of a moment of audio with the Web Audio API. The only things which connect to intensity which I found in the specification are the:

analyser.minDecibels
analyser.maxDecibels

Is there a way to do this?


Solution

  • If I understand correctly, you want a number that is high when the sound is loud, and low when the sound is quiet. You can use the "Sound Pressure Level" for that.

    Getting this number from the Web Audio API is rather straightforward, and you had guessed correctly that we will use the AnalyserNode to achieve this. Here is a example code that shows you how to do it:

    var ac = new AudioContext();
    /* create the Web Audio graph, let's assume we have sound coming out of the
     * node `source` */
    var an = ac.createAnalyser();
    source.connect(an);
    /* Get an array that will hold our values */
    var buffer = new Uint8Array(an.fftSize);
    
    function f() {
      /* note that getFloatTimeDomainData will be available in the near future,
       * if needed. */
      an.getByteTimeDomainData(buffer);
      /* RMS stands for Root Mean Square, basically the root square of the
      * average of the square of each value. */
      var rms = 0;
      for (var i = 0; i < buffer.length; i++) {
        rms += buffer[i] * buffer[i];
      }
      rms /= buffer.length;
      rms = Math.sqrt(rms);
      /* rms now has the value we want. */
      requestAnimationFrame(f);
    }
    
    requestAnimationFrame(f);
    /* start our hypothetical source. */
    source.start(0);