getUserMedia
This lesson explains getUserMedia with clear examples, use cases, and best practices so you can use HTML5 APIs confidently in real web applications.
HTML5 MediaDevices getUserMedia() API Overview
The HTML5 MediaDevices API provides access to a device's camera,
microphone, and other media input devices. The
navigator.mediaDevices.getUserMedia() method requests
permission from the user and returns a live
MediaStream that can be displayed, recorded, or processed.
The API is widely used in video conferencing, online meetings, barcode
scanners, QR code readers, document scanners, live streaming, webcam
applications, voice recording, facial recognition, AR experiences, and
browser-based media applications.
| Feature | Description |
| API Name | MediaDevices getUserMedia API |
| Main Object | navigator.mediaDevices |
| Main Method | getUserMedia() |
| Returns | Promise<MediaStream> |
| Permissions | Camera and/or microphone permission |
| HTTPS Required | Yes (except localhost) |
Access Webcam
<video
id="camera"
autoplay
playsinline>
</video>
<script>
async function startCamera() {
try {
const stream =
await navigator.mediaDevices
.getUserMedia(
{
video: true
}
);
document
.querySelector("#camera")
.srcObject = stream;
} catch (error) {
console.error(error);
}
}
startCamera();
</script>
This example requests access to the user's camera and displays the live
video inside a <video> element.
Method Syntax
navigator.mediaDevices
.getUserMedia(
{
video: true,
audio: true
}
)
.then((stream) => {
console.log(stream);
})
.catch((error) => {
console.error(error);
});
The method accepts a constraints object that specifies which media devices
are requested.
Media Constraints
| Constraint | Description | Example |
video | Enable camera. | true |
audio | Enable microphone. | true |
width | Preferred video width. | 1920 |
height | Preferred video height. | 1080 |
facingMode | Select front or rear camera. | user, environment |
frameRate | Preferred FPS. | 30 |
Access Camera and Microphone
async function startMedia() {
const stream =
await navigator.mediaDevices
.getUserMedia(
{
video: true,
audio: true
}
);
document
.querySelector("video")
.srcObject = stream;
}
This example requests both camera and microphone access for video calls
and conferencing applications.
Request HD Video
navigator.mediaDevices
.getUserMedia(
{
video: {
width: 1920,
height: 1080,
frameRate: 30
}
}
);
Constraints are treated as preferences. The browser chooses the closest
supported configuration for the selected camera.
Select Front or Rear Camera
// Front camera
navigator.mediaDevices
.getUserMedia(
{
video: {
facingMode: "user"
}
}
);
// Rear camera
navigator.mediaDevices
.getUserMedia(
{
video: {
facingMode: "environment"
}
}
);
Mobile devices often provide both front and rear cameras using the
facingMode constraint.
Stop Camera
const tracks =
stream.getTracks();
tracks.forEach((track) => {
track.stop();
});
Always stop media tracks when the application no longer needs camera or
microphone access to save battery and respect user privacy.
List Available Devices
navigator.mediaDevices
.enumerateDevices()
.then((devices) => {
devices.forEach((device) => {
console.log(
device.kind,
device.label
);
});
});
The enumerateDevices() method lists available cameras,
microphones, and audio output devices. Device labels are usually available
only after the user grants permission.
MediaStream Properties and Methods
| Property / Method | Description |
getTracks() | Returns all media tracks. |
getVideoTracks() | Returns video tracks. |
getAudioTracks() | Returns audio tracks. |
active | Indicates whether the stream is active. |
id | Unique stream identifier. |
Capture a Video Frame
const canvas =
document.querySelector("canvas");
const context =
canvas.getContext("2d");
context.drawImage(
document.querySelector("video"),
0,
0,
canvas.width,
canvas.height
);
A video frame can be copied onto a canvas and then exported as an image
using Canvas APIs.
Permission Handling
try {
await navigator.mediaDevices
.getUserMedia(
{
video: true
}
);
} catch (error) {
console.log(error.name);
}
| Error | Meaning |
NotAllowedError | User denied permission. |
NotFoundError | No camera or microphone available. |
NotReadableError | Device is already in use. |
AbortError | Media request failed. |
SecurityError | Security restriction prevented access. |
Feature Detection
if (
"mediaDevices" in navigator &&
"getUserMedia" in navigator.mediaDevices
) {
console.log(
"Camera API supported."
);
} else {
console.log(
"Camera API unavailable."
);
}
Common getUserMedia() Use Cases
| Application | Purpose |
| Video Conferencing | Capture webcam and microphone. |
| Voice Recording | Capture microphone input. |
| QR Code Scanner | Read QR codes using the camera. |
| Barcode Scanner | Scan retail products. |
| Document Scanner | Capture paper documents. |
| Live Streaming | Capture live camera feed. |
| AR Applications | Use the camera for augmented reality. |
| Facial Recognition | Process live camera images. |
getUserMedia() Best Practices
- Always use HTTPS in production.
- Request only the permissions your application actually needs.
- Stop media tracks when they are no longer required.
- Handle permission denial gracefully.
- Use feature detection before calling the API.
- Allow users to switch between available cameras.
- Provide clear indicators when the camera or microphone is active.
- Optimize video resolution based on network conditions.
Privacy and Security Considerations
- Never access media devices without user permission.
- Clearly explain why camera or microphone access is needed.
- Do not store recordings without user consent.
- Stop recording immediately when the user ends the session.
- Use encrypted HTTPS connections.
- Inform users whenever recording is active.
Common getUserMedia() Mistakes
- Requesting unnecessary camera and microphone permissions.
- Forgetting to stop media tracks.
- Ignoring rejected Promises.
- Not handling missing devices.
- Assuming every device supports HD video.
- Ignoring browser compatibility and permissions.
- Using HTTP instead of HTTPS.
- Not informing users when recording starts.
getUserMedia() vs File Upload
| Feature | getUserMedia() | File Upload |
| Live Camera | ✔ Yes | ✘ No |
| Microphone | ✔ Yes | ✘ No |
| User Permission | Required | Not required |
| Real-Time Processing | ✔ Yes | Limited |
| Offline File Selection | ✘ No | ✔ Yes |
Key Takeaways
getUserMedia() provides access to the camera and microphone. - It returns a
MediaStream object. - Always request permission through a user action.
- Stop media tracks when finished.
- Use HTTPS and feature detection.
- Respect user privacy and clearly communicate media usage.
Pro Tip
The getUserMedia() API is often combined with the
MediaRecorder API, WebRTC, Canvas API, WebCodecs, Barcode Detection API,
Face Detection libraries, and Web Speech API to build powerful browser
applications such as video conferencing, scanners, live streaming, and
AI-powered camera experiences.