shrey shah
shrey shah

Reputation: 111

How to check Microphone Volume in Angular

I wanted to check microphone volume in my Angular, are there any plugins or libraries which I can use?

let mic = navigator.mediaDevices.getUserMedia({ audio: true });
mic.then(function () {
  alert('Mic Is Connected');
}).catch(function () {
  alert('Mic Is Not Connected');
});

I am testing if my Microphone is connected or not by above code, now I want a real time volume meter here

Upvotes: 1

Views: 2622

Answers (2)

sçuçu
sçuçu

Reputation: 3070

Your need is not Angular specific, to note.

audioEl.addEventListener('volumechange', (event) => {
  console.log('The volume changed.');
  // here you can use the volumechange event or the volume attribute of the element.
});

You need to get the tracks inside the stream. Then get the current settings of these tracks. Then you will need to get the volume from each setings. Although the volume property of settngs looks like obsolete in MDN documentation, I have not been able to find another way.

navigator.mediaDevices.getUserMedia({ audio: true })
  .then(function (stream) {
    alert('Mic Is Connected');
    const tracks = stream.getTracks();
    const settings = tracks.map(track => track.getSettings());
    const volumes = settings.map(setting => setting.volume);
    console.log("volumes: ", volumes);
}).catch(function () {
  alert('Mic Is Not Connected');
});

Also you can add this stream as srcObject to an audio element and then get the volume attribute. Docs

navigator.mediaDevices.getUserMedia({ audio: true })
    .then(function (stream) {
      alert('Mic Is Connected');
      const audioEl = document.createElement('audio');
      audioEl.srcObject = stream;
      const volume = audioEl.getAttribute('volume');
      console.log("volume: ", volume);
    }).catch(function () {
      alert('Mic Is Not Connected');
    });

And there might be a Web Audio API specific audio context way too.

Upvotes: 0

sudomudo
sudomudo

Reputation: 94

You can use a package avaliable in angular named 'decibal-meter', which will give you the decibels captured on your microphone.

First of all Install decibal meter in your angular project,

npm install --save decibel-meter

After Installation import decibal meter in your component.ts file,

import DecibelMeter from 'decibel-meter'

Use the below code which will give you the result for your microphone volume

decibals = 0;
const meter = new DecibelMeter('mictest');

meter.sources.then(sources => {
  meter.connect(sources[0]);
  meter.listenTo(0, (dB, percent) => this.decibals = Number(`${dB}`) + 100);

});

By this code you will get the decibals value and those values you can store it in a variable and you can access that variable in your HTML file.

For displaying those decibels value you can use a progress bar which will look like sound/volume meter

You can also refer to the official documentation for the decibel-meter, decibel-meter - NPM

Upvotes: 2

Related Questions