How to detect that system connected with microphon

2019-03-01 06:09发布

问题:

I'm using getUserMedia() for audio recording and it works correctly but have an issue with it.

I want to display a message before starting recording that any microphone is connected with system or not.

For this I have used following code and run this into chrome but it was not working correctly.

if(navigator.getUserMedia || navigator.webkitGetUserMedia)
{
   alert("Microphone is connected with your system");
} else {
   alert("Microphone is not connected with your system");
}

when microphone is not connected then also above code giving message "Microphone is connected with your system".

so please suggest me a better way to detect microphone using JavaScript in any browser.

回答1:

Testing for the existence of these functions does not detect the existence of hardware microphone. It only detects if browser has the API to do so.

The browsers that pass your test need not have a physical microphone plugged into microphone jack. It is simply a newer browser. The browsers that fail the test may have a microphone, but are old browsers that do not contain the API.

Also, at least the getUserMedia function is asynchronous, so any code that depends on using the audio or video must be put in a callback function, not the main script.

See https://developer.mozilla.org/en-US/docs/Web/API/Navigator.getUserMedia for an example of how to write cross-browser code for audio/video input.



回答2:

Something like this :

function succes(stream) {

   // we has it

}

function fail(error) {

   console.log(error);

   if (error === 'NO_DEVICES_FOUND') {

      // NO_DEVICES_FOUND (no microphone og microphone disabled)

   }

}

navigator.getUserMedia({audio : true}, succes, fail);