Checking microphone volume in Javascript

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 = new AudioContext();
    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 = new Uint8Array(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.

function colorPids(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:

<div class="pids-wrapper">
  <div class="pid"></div>
  <div class="pid"></div>
  <div class="pid"></div>
  <div class="pid"></div>
  <div class="pid"></div>
  <div class="pid"></div>
  <div class="pid"></div>
  <div class="pid"></div>
  <div class="pid"></div>
  <div class="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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)