Skip to content Skip to sidebar Skip to footer

Checking Microphone Volume In Javascript

I'm trying to make a little game that needs access to the users mic. I need to be able to check if a mic is connected, and then if so, check the volume of the sound coming through

Solution 1:

A slightly more detailed answer after having to work it out myself feel may help others looking here.

This following code will log out a number of approx 0 to 100 based on the microphone volume.

navigator.mediaDevices.getUserMedia({
  audio: true,
  video: true
})
  .then(function(stream) {
    const audioContext = newAudioContext();
    const analyser = audioContext.createAnalyser();
    const microphone = audioContext.createMediaStreamSource(stream);
    const scriptProcessor = audioContext.createScriptProcessor(2048, 1, 1);

    analyser.smoothingTimeConstant = 0.8;
    analyser.fftSize = 1024;

    microphone.connect(analyser);
    analyser.connect(scriptProcessor);
    scriptProcessor.connect(audioContext.destination);
    scriptProcessor.onaudioprocess = function() {
      const array = newUint8Array(analyser.frequencyBinCount);
      analyser.getByteFrequencyData(array);
      const arraySum = array.reduce((a, value) => a + value, 0);
      const average = arraySum / array.length;
      console.log(Math.round(average));
      // colorPids(average);
    };
  })
  .catch(function(err) {
    /* handle the error */console.error(err);
  });

If you have this number jquery to style blocks of color. An example function of this i have provided below but that is the easy part. Just un-comment out the color pids function.

functioncolorPids(vol) {
  const allPids = [...document.querySelectorAll('.pid')];
  const numberOfPidsToColor = Math.round(vol / 10);
  const pidsToColor = allPids.slice(0, numberOfPidsToColor);
  for (const pid of allPids) {
    pid.style.backgroundColor = "#e6e7e8";
  }
  for (const pid of pidsToColor) {
    // console.log(pid[i]);
    pid.style.backgroundColor = "#69ce2b";
  }
}

To make sure this answer is as detailed as possible i have also attached my html and css below so you can just copy the js html and css if you wish to get a working example up and running.

html:

<divclass="pids-wrapper"><divclass="pid"></div><divclass="pid"></div><divclass="pid"></div><divclass="pid"></div><divclass="pid"></div><divclass="pid"></div><divclass="pid"></div><divclass="pid"></div><divclass="pid"></div><divclass="pid"></div></div>

css:

.pids-wrapper{
  width: 100%;
}
.pid{
  width: calc(10% - 10px);
  height: 10px;
  display: inline-block;
  margin: 5px;
}

After all that you will end up with something like this. enter image description here

Solution 2:

Here is an answer simply using setTimeout instead of the deprecated createScriptProcessor function:

(async () => {
  let volumeCallback = null;
  let volumeInterval = null;
  const volumeVisualizer = document.getElementById('volume-visualizer');
  const startButton = document.getElementById('start');
  const stopButton = document.getElementById('stop');
  // Initializetry {
    const audioStream = await navigator.mediaDevices.getUserMedia({
      audio: {
        echoCancellation: true
      }
    });
    const audioContext = newAudioContext();
    const audioSource = audioContext.createMediaStreamSource(audioStream);
    const analyser = audioContext.createAnalyser();
    analyser.fftSize = 512;
    analyser.minDecibels = -127;
    analyser.maxDecibels = 0;
    analyser.smoothingTimeConstant = 0.4;
    audioSource.connect(analyser);
    const volumes = newUint8Array(analyser.frequencyBinCount);
    volumeCallback = () => {
      analyser.getByteFrequencyData(volumes);
      let volumeSum = 0;
      for(const volume of volumes)
        volumeSum += volume;
      const averageVolume = volumeSum / volumes.length;
      // Value range: 127 = analyser.maxDecibels - analyser.minDecibels;
      volumeVisualizer.style.setProperty('--volume', (averageVolume * 100 / 127) + '%');
    };
  } catch(e) {
    console.error('Failed to initialize volume visualizer, simulating instead...', e);
    // Simulation//TODO remove in production!let lastVolume = 50;
    volumeCallback = () => {
      const volume = Math.min(Math.max(Math.random() * 100, 0.8 * lastVolume), 1.2 * lastVolume);
      lastVolume = volume;
      volumeVisualizer.style.setProperty('--volume', volume + '%');
    };
  }
  // Use
  startButton.addEventListener('click', () => {
    // Updating every 100ms (should be same as CSS transition speed)if(volumeCallback !== null && volumeInterval === null)
      volumeInterval = setInterval(volumeCallback, 100);
  });
  stopButton.addEventListener('click', () => {
    if(volumeInterval !== null) {
      clearInterval(volumeInterval);
      volumeInterval = null;
    }
  });
})();
div {
  --volume: 0%;
  position: relative;
  width: 200px;
  height: 20px;
  margin: 50px;
  background-color: #DDD;
}

div::before {
   content: '';
   position: absolute;
   top: 0;
   bottom: 0;
   left: 0;
   width: var(--volume);
   background-color: green;
   transition: width 100ms linear;
}

button {
  margin-left: 50px;
}

h3 {
  margin: 20px;
  font-family: sans-serif;
}
<h3><b>NOTE:</b> This is not accurate on stackoverflow, since microphone use is not permitted. It's a simulation instead.</h3><divid="volume-visualizer"></div><buttonid="start">Start</button><buttonid="stop">Stop</button>

This also means, that it can easily be started and stopped on demand.

Solution 3:

Here is the snippet needed to detect audio controls are available (pulled from: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/getUserMedia)

navigator.getUserMedia(constraints, successCallback, errorCallback);

Here is a sample using the getUserMedia function that will enable you access to the microphone.

navigator.getUserMedia = navigator.getUserMedia ||
                     navigator.webkitGetUserMedia ||
                     navigator.mozGetUserMedia;

if (navigator.getUserMedia) {
   navigator.getUserMedia({ audio: true, video: { width: 1280, height: 720 } },
      function(stream) {
         console.log("Accessed the Microphone");
      },
      function(err) {
         console.log("The following error occured: " + err.name);
      }
    );
} else {
   console.log("getUserMedia not supported");
}

Here is a repository that demonstrates the "input volume" you desire.

https://github.com/cwilso/volume-meter/

Solution 4:

Simple Microphone Vu Meter See https://codepen.io/www-0av-com/pen/jxzxEX

Checked and working in 2018, including bug fix caused by security update in Chrome browser.

HTML <h3>VU meter from mic input (getUserMedia API)</h3> <button onclick="startr();" title="click start needed as security in browser increased and voice mic can only be started from a gesture on page">Start</button> <canvas id="canvas" width="150" height="300" style='background:blue'></canvas> <br> CLICK START <div align=left>See JS for attribution</div>

CSS

body {
  color: #888;
  background: #262626;
  margin: 0;
  padding: 40px;
  text-align: center;
  font-family: "helvetica Neue", Helvetica, Arial, sans-serif;
}

#canvas {
  width: 150px;
  height: 100px;
  position: absolute;
  top: 150px;
  left: 45%;
  text-align: center;
}

JS (needs JQuery)

// Courtesy www/0AV.com, LGPL license or as set by forked host, Travis Holliday, https://codepen.io/travisholliday/pen/gyaJk functionstartr(){
 console.log ("starting...");
 navigator.getUserMedia = navigator.getUserMedia ||
   navigator.webkitGetUserMedia ||
   navigator.mozGetUserMedia;
 if (navigator.getUserMedia) {
  navigator.getUserMedia({
      audio: true
    },
    function(stream) {
      audioContext = newAudioContext();
      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);

      canvasContext = $("#canvas")[0].getContext("2d");

      javascriptNode.onaudioprocess = function() {
          var array = newUint8Array(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;

//          console.log(Math.round(average - 40));

          canvasContext.clearRect(0, 0, 150, 300);
          canvasContext.fillStyle = '#BadA55';
          canvasContext.fillRect(0, 300 - average, 150, 300);
          canvasContext.fillStyle = '#262626';
          canvasContext.font = "48px impact";
          canvasContext.fillText(Math.round(average - 40), -2, 300);
          // console.log (average);
        } // end fn stream
    },
    function(err) {
      console.log("The following error occured: " + err.name)
    });
} else {
  console.log("getUserMedia not supported");
 }
}

Post a Comment for "Checking Microphone Volume In Javascript"