# getUserMedia()

> The `getUserMedia()` JS method asks the user for permission to use the microphone or camera and returns a `MediaStream`.

## How do I access the microphone in JavaScript?

The method of `navigator.mediaDevices` that requests access to the microphone and camera and returns a promise with a `MediaStream`. Works only in secure contexts and shows a permission prompt to the user.

- Topic: Media & Audio
- Type: method
- Browser support: Chrome 53+, Chrome Android 53+, Edge 12+, Firefox 36+, Firefox Android 36+, Safari 11+, Safari iOS 11+

## Example

Wrong:

```js
const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true });
audio.srcObject = stream;
```

Right:

```js
try {
  const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
  audio.srcObject = stream;
} catch (err) {
  if (err.name === 'NotAllowedError') showPermissionHint();
}
```

Request only the microphone and handle a denied permission instead of leaving the promise rejection unhandled.

## Common mistakes

- Testing over plain HTTP, where the API is unavailable.

## Key points

- The call is wrapped in `try...catch` and handles 'NotAllowedError' when permission is denied.
- Access is requested after a user action, not automatically on page load.
- Only the needed devices are requested, for example `{ audio: true }` without video.

## Interview questions

### Why is `navigator.mediaDevices` undefined?

The API exists only in secure contexts, so the page must be served over HTTPS or from `localhost`.

### How do I turn off the camera or microphone after `getUserMedia()`?

Call `stop()` on every track: `stream.getTracks().forEach((t) => t.stop())`. The recording indicator turns off once all tracks stop.

### Can I choose a specific microphone?

Yes. List devices with `enumerateDevices()` and pass `{ audio: { deviceId: { exact: id } } }` to `getUserMedia()`.

## Related cards

- [MediaStream](https://wonderium.dev/js/media-stream.md)
- [navigator.mediaDevices](https://wonderium.dev/js/navigator-media-devices.md)
- [navigator.permissions](https://wonderium.dev/js/navigator-permissions.md)

---

- Level: [JavaScript](https://wonderium.dev/js.md)
- HTML version: https://wonderium.dev/js/get-user-media
- Last updated: 2026-11-25
