Categories
JavaScript Answers

How to access microphone from a browser with JavaScript?

Spread the love

Sometimes, we want to access microphone from a browser with JavaScript.

In this article, we’ll look at how to access microphone from a browser with JavaScript.

How to access microphone from a browser with JavaScript?

To access microphone from a browser with JavaScript, we use the navigator.mediaDevices.getUserMedia method.

For instance, we write

const getMedia = async (constraints) => {
  let stream = null;
  try {
    stream = await navigator.mediaDevices.getUserMedia(constraints);
    console.log(stream);
  } catch (err) {
    document.write(err);
  }
};

getMedia({ audio: true, video: true });

to define the getMedia function.

In it, we call navigator.mediaDevices.getUserMedia with the constraints object with the options for what to get permission for.

It returns a promise with the stream.

We call getMedia with { audio: true, video: true } to get access to the microphone and camera.

Conclusion

To access microphone from a browser with JavaScript, we use the navigator.mediaDevices.getUserMedia method.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.