How to detect that system connected with microphone using JavaScript

我怕爱的太早我们不能终老 提交于 2019-12-02 07:17:31

问题


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);



回答3:


Try this

   navigator.mediaDevices.getUserMedia({ audio: true })
            .then(stream => {
            // Code for success
            }).catch(err => {
                if(err.includes("NotFoundError: Requested device not found"))
                alert("Mic not detected")
                else alert("Error recording audio")
            })

If the mic is not detected or unplugged means the catch statement will be executed. You can show your error message here.



来源:https://stackoverflow.com/questions/22706099/how-to-detect-that-system-connected-with-microphone-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!