Camera and microphone
The preview will appear here after you grant camera access.
Activate the control to request camera and microphone access.
Explore <usermedia> as a trusted, browser-managed control for requesting camera and microphone access. Configure setConstraints(), connect the MediaStream to a preview, and compare the native element with progressive enhancement based on getUserMedia().
The preview will appear here after you grant camera access.
Activate the control to request camera and microphone access.
<section class="usermedia-demo" aria-labelledby="usermedia-title">
<h2 id="usermedia-title">Camera and microphone</h2>
<div class="stream-preview">
<video
id="media-preview"
autoplay
playsinline
muted
hidden
aria-label="Camera preview"
></video>
<p data-media-placeholder>The preview will appear here after you grant camera access.</p>
</div>
<div class="media-actions">
<usermedia id="media-control" aria-describedby="media-status">
<button type="button" id="fallback-media-control">
Enable camera and microphone
</button>
</usermedia>
<button type="button" id="stop-media" disabled>
Stop capture
</button>
</div>
<p id="media-status" role="status" aria-live="polite">
Activate the control to request camera and microphone access.
</p>
</section>const mediaControl = document.querySelector('#media-control');
const fallbackButton = document.querySelector('#fallback-media-control');
const videoPreview = document.querySelector('#media-preview');
const placeholder = document.querySelector('[data-media-placeholder]');
const stopButton = document.querySelector('#stop-media');
const status = document.querySelector('#media-status');
const constraints = {
video: {
width: 1280,
height: 720,
facingMode: "user",
frameRate: 30,
},
audio: {
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true,
},
};
let currentStream = null;
const showStatus = (message) => {
status.textContent = message;
};
const attachStream = (stream) => {
if (!stream) return;
currentStream = stream;
videoPreview.srcObject = stream;
videoPreview.hidden = false;
placeholder.hidden = true;
stopButton.disabled = false;
showStatus("Capture is active. Video is muted to prevent feedback.");
};
const stopStream = () => {
currentStream?.getTracks().forEach((track) => track.stop());
currentStream = null;
videoPreview.srcObject = null;
videoPreview.hidden = true;
placeholder.hidden = false;
stopButton.disabled = true;
showStatus("Capture has stopped.");
};
if ('HTMLUserMediaElement' in window) {
mediaControl.setConstraints(constraints);
mediaControl.addEventListener('stream', () => {
attachStream(mediaControl.stream);
});
mediaControl.addEventListener('error', () => {
const errorName = mediaControl.error?.name ?? 'UnknownError';
showStatus(`Capture could not start: ${errorName}.`);
});
mediaControl.addEventListener('cancel', () => {
showStatus("The permission request was cancelled.");
});
} else {
fallbackButton.addEventListener('click', async () => {
if (!navigator.mediaDevices?.getUserMedia) {
showStatus("Media capture is unavailable in this context or browser.");
return;
}
showStatus("Waiting for the browser…");
try {
attachStream(await navigator.mediaDevices.getUserMedia(constraints));
} catch (error) {
const errorName = error instanceof DOMException ? error.name : 'UnknownError';
showStatus(`Capture could not start: ${errorName}.`);
}
});
}
stopButton.addEventListener('click', stopStream);Educational guide to usermedia
Distinguish <usermedia> from getUserMedia(), configure preferences, and connect tracks to a preview. Learn to handle permissions, errors, and capture cleanup with a progressive fallback.
The control requests access; the stream provides tracks; your application decides how to use and release them.
A person activates a visible control and the browser handles consent and acquisition.
The stream event lets you read the element’s stream property and connect audio and video to the application.
The application stops each track when it no longer needs it and removes the preview reference.
A stream is not a recording or a network connection. It groups media tracks you can display, process, record with another API, or send through an explicit connection. Assigning it to video.srcObject only connects that source to the local player.
They share a result type, but differ in who initiates and presents the request.
<usermedia> offers a browser-managed control to acquire camera and microphone together. Configure setConstraints() and listen for stream, error, and cancel. When stream fires, read element.stream: the event is not the MediaStream object, and you should not start an additional getUserMedia() call.
getUserMedia() returns a Promise and leaves the button, states, and failure handling to your application. It is the alternative for browsers without the element and for audio-only or video-only capture. Do not transfer audio: false or video: false to the <usermedia> contract: its audio/video options are dictionaries, and the element covers both tracks.
Child text belongs to the fallback; it does not control the native button label, which the browser chooses. Avoid treating this trusted control as an arbitrary button: the browser may restrict styling, size, contrast, or occlusion and disable a presentation it considers invalid.
Support, granted permission, and an available device are separate conditions.
Serve capture from a secure context, usually HTTPS; localhost enables local development. Explain the purpose before requesting access and tie the fallback to an explicit action. These recipes omit autostart and do not call getUserMedia() on load. Configuring preferences does not start capture.
In an iframe, check the camera and microphone Permissions Policy directives, delegation from the parent document, and relevant allow/sandbox attributes. An allow cannot override a stricter header or grant permission on someone’s behalf. Browser or operating-system restrictions and a busy device can also prevent capture.
Denial is not solved by requesting access in a loop. Offer instructions to review site and system permissions, keep the rest of the interface usable, and let people choose to retry. Detecting HTMLUserMediaElement does not confirm that the next capture will succeed.
A local preview, a stop action, and two paths to the same stream type.
This recipe reuses the playground’s HTML and JavaScript with its initial configuration. A supporting browser shows the native control; otherwise, activating the child button calls getUserMedia(). Copy both blocks and load JavaScript after the HTML, for example as a module. Decorative CSS is unnecessary.
muted prevents local microphone playback, but does not disable it: the stream retains its audio track. playsinline helps keep video playback inline. Neither permission nor autoplay guarantees playback in every environment; check real behaviour. This recipe is a starting point: an integration must also handle pending requests, stream replacement, and unmounting.
Requesting HD does not prove the camera delivers HD, and constraint contracts are not identical.
In the recipe, width, height, facingMode, and frameRate are preferences, subject to the device and browser. Configure setConstraints() before interaction. The element proposal filters required constraints; do not assume exact, min, max, or advanced transfer as they do with getUserMedia(). setConstraints() does not modify a track that is already capturing either.
The second object illustrates an imperative API requirement: demanding a minimum width of 1280 pixels can cause OverconstrainedError before a prompt. No request runs here. In getUserMedia(), ideal or a plain value expresses a preference; min, max, and exact impose requirements. Do not mistake that error for permission denial.
After acquisition, read track.getSettings() for each track’s actual settings. getSupportedConstraints() identifies keys the browser understands, not the capabilities of a particular camera. To renegotiate a track, use applyConstraints(), handle rejection, and read getSettings() again; a preset does not promise an exact resolution, camera, or audio processing configuration.
A microphone-only check demonstrates the lifecycle without requesting a camera or playing back your voice.
This independent recipe uses getUserMedia({ audio: true, video: false }) to check the microphone. It blocks duplicate activation, lets you stop a pending request, and releases a stream that arrives after that stop. State changes are announced with role="status" without moving focus.
Stop does not close the prompt or cancel the Promise: it invalidates the response and stops its tracks if they arrive later. A request can remain pending if someone ignores it. Also call cleanup when unmounting a SPA view; pagehide covers leaving the page, not every internal navigation.
video.pause(), video.hidden, or srcObject = null do not stop tracks. Call stop() on every track your flow owns and clear references. stop() sets readyState to ended without firing ended: update the interface directly. The ended event handles external endings such as revocation. Stopping a track does not revoke permission, and other tracks or tabs may still use the device.
Identify the failing stage before changing constraints or requesting access again.
Separate the element, the capture API, and device capabilities.
As checked on 22 October 2026, Chrome documents <usermedia> from version 151. MDN BCD records that addition and no Firefox or Safari support; the element remains experimental and has limited availability. Its draft can evolve: a proposal does not imply interoperable support.
getUserMedia() and MediaStreamTrack.stop() are widely available. This does not guarantee permission, hardware, playback, or every constraint. Detect the element, keep the fallback button, and also check navigator.mediaDevices?.getUserMedia; if it is absent, show an explanation rather than pretending to capture.
Verify keyboard, focus, zoom, screen readers, and real devices for both the native control and fallback. The guide does not simulate granted permission or test hardware for you; use the playground only when you intend to start real capture.