Lesson 6 of 9 · 25m
Media Capture, Constraints, and Permissions
Acquire camera and microphone predictably, translate user intent into track constraints, handle permission denial, and avoid device churn footguns.
Most WebRTC demos start with getUserMedia({video: true, audio: true}) and end the moment a real user has two webcams, a Bluetooth headset, a denied permission, a corporate browser policy, and an operating system privacy indicator they do not trust. Capture is product behavior, not an initialization detail.
Ask for what the experience needs
Constraints are not resolution wishes pasted from a blog post. They express tradeoffs:
const stream = await navigator.mediaDevices.getUserMedia({
audio: {echoCancellation: true, noiseSuppression: true, autoGainControl: true, channelCount: 1},
video: {width: {ideal: 1280, max: 1920}, height: {ideal: 720, max: 1080},
frameRate: {ideal: 30, max: 30}, facingMode: "user"},
});exact means failure if unavailable. ideal means preference. Teams often request 1080p by default and then spend months debugging thermal throttling, encoder overload, and upstream bandwidth collapse. Start lower; scale up deliberately.
Permission errors have distinct meanings
try {
stream = await navigator.mediaDevices.getUserMedia(constraints);
} catch (err) {
if (err.name === "NotAllowedError") showPermissionHelp();
else if (err.name === "NotFoundError") showNoDeviceHelp();
else if (err.name === "NotReadableError") showDeviceBusyHelp();
else if (err.name === "OverconstrainedError") showFallbackChoice(err.constraint);
else showGenericCaptureError(err);
}NotAllowedError can mean the user denied, the browser policy denied, or the page is not in a secure context. NotReadableError often means another application or OS-level control owns the device. These require different support instructions.
Device labels require permission state
enumerateDevices() is privacy-sensitive. Before persistent permission, labels may be empty even though IDs exist:
const devices = await navigator.mediaDevices.enumerateDevices();
for (const d of devices) console.log(d.kind, d.deviceId, d.label);Store deviceId preferences after permission, but handle disappearance gracefully. Browser privacy modes, profile changes, and device reconnection can invalidate them. The right fallback is usually default device plus user confirmation, not a dead settings screen.
Muting is not stopping
A mute button should normally disable a track:
audioTrack.enabled = false; // keeps device open, stops meaningful output
videoTrack.enabled = false; // keeps camera allocated but sends black framesStopping is different:
videoTrack.stop(); // releases the device when no clone remainsIf the camera light stays on while your UI says video is off, users will assume surveillance or incompetence. Decide which semantic you promise. For privacy-sensitive pause, stop video and reacquire on resume; for instant mute, disable audio but be transparent that the microphone remains allocated.
Screen share is a separate trust surface
getDisplayMedia() requires a user gesture in modern browsers:
const screen = await navigator.mediaDevices.getDisplayMedia({
video: {frameRate: {ideal: 15, max: 30}},
audio: false,
});
screen.getVideoTracks()[0].onended = () => stopPresenting();The browser chooser determines what is shared. You cannot inspect a thumbnail and guarantee the user selected the intended window. Warn before sharing, render local preview, and provide a visually obvious stop control.
Device churn needs reconciliation
Listen for devicechange, but debounce it. A laptop dock can trigger multiple events while USB audio, cameras, and Bluetooth routes settle. Rebuild the device list, preserve selection when stable IDs persist, and only auto-switch input when the current device disappeared or the user explicitly chose system-default behavior.
Field notes
getUserMediarequires HTTPS or localhost in modern browsers; embedded webviews may impose additional permission plumbing.- Bluetooth audio can alter sample rates and profile behavior. Test the cheap headset, not just studio hardware.
applyConstraints()can reconfigure an active track, but device support varies and failure must not tear down the call silently.- Never auto-play remote audio without considering browser autoplay policy. User activation and explicit unmute UX are part of call reliability.
Was this lesson helpful?