How to detect that system connected with microphone using JavaScript

柔情痞子 提交于 2019-12-02 02:56:17

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.

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

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.

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