Search code examples
javascriptaudio

How to get Volume level using JavaScript?


I developed one web-based monitoring system Using js and WebRTC and now I want to develop notification function if the sound goes beyond some level.

I'm taking permission for video and audio and after permission, I want to use the function for sound notification.

navigator.mediaDevices
  .getUserMedia({
    audio: true,
    video: true
  })
  .then(stream => {
    // Display your local video in #localVideo element
    localVideo.srcObject = stream;
    // Add your stream to be sent to the conneting peer
    pc.addStream(stream);
    // call function for sound check
  }, onError);

Solution

  • You can use this code.

    <!DOCTYPE html>
    <html>
    <head>
    <script>
      navigator.mediaDevices.getUserMedia({ audio: true }).then(function(stream) {
      audioContext = new AudioContext();
      analyser = audioContext.createAnalyser();
      microphone = audioContext.createMediaStreamSource(stream);
      javascriptNode = audioContext.createScriptProcessor(2048, 1, 1);
      analyser.smoothingTimeConstant = 0.8;
      analyser.fftSize = 1024;
      microphone.connect(analyser);
      analyser.connect(javascriptNode);
      javascriptNode.connect(audioContext.destination);
      javascriptNode.onaudioprocess = function() {
          var array = new Uint8Array(analyser.frequencyBinCount);
          analyser.getByteFrequencyData(array);
          var values = 0;
    
          var length = array.length;
          for (var i = 0; i < length; i++) {
            values += (array[i]);
          }
    
          var average = values / length;
    
          if(Math.round(average)>15)
          {
            console.log(Math.round(average));
            document.getElementById("lvl").innerHTML = Math.round(average)-10;
          }
        
      }
      })
      .catch(function(err) {
        /* handle the error */
    });
    </script>
    </head>
    <center><p id="lvl" style="font-size:200px"></p><center>
    </html>
    

    Copy and make it an HTML file and open it in chrome and make some sound. You will come to know how it's work and if it is the same as you need copy function from the 5th line and make it one separate function and call this function is your code.

    Hope it's work for you