Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 36 ยท Media Capture and Streams

Constraints and Devices

Control capture with media constraints (ideal, exact, min, max), list cameras and microphones with enumerateDevices, switch devices, and tune audio processing.

Asking for "any camera" is fine for a demo. Real apps need more control: HD video on a laptop but smaller on a phone, the back camera on a phone, a specific microphone, no echo cancellation for a music lesson. Constraints are how you describe what you want, and enumerateDevices() is how you find out what exists.

The preview has no real devices, so the device-listing code is read-only here. The runnable examples use constraints on a synthetic canvas track (browsers apply applyConstraints to it too) and the getSupportedConstraints() report, which works everywhere.

Constraint values: exact, ideal, min and max

Each property accepts a plain value or an object:

JavaScript
const constraints = {
  video: {
    width:  { min: 640, ideal: 1280, max: 1920 },
    height: { ideal: 720 },
    frameRate: { ideal: 30, max: 30 },
    facingMode: 'user',                   // front camera (preference)
  },
  audio: { echoCancellation: true, noiseSuppression: true },
};
Form Meaning If it cannot be met
1280 or { ideal: 1280 } Prefer this, get as close as possible Falls back silently
{ exact: 1280 } Must be exactly this Rejects with OverconstrainedError
{ min: 640 } / { max: 1920 } Bounds Rejects if no device is in range

Prefer ideal. Using exact for resolution breaks on devices that do not offer that exact mode; reserve it for things you truly cannot do without, such as a specific deviceId.

facingMode accepts user (selfie camera), environment (back camera), left and right. On desktops with one camera it is ignored unless you use exact.

What is supported?

Not every browser supports every constraint. Ask:

Supported constraints

Unsupported constraints in the object are ignored without error (unless you mark them exact), so a typo such as framerate silently does nothing. Check spelling against this list.

Reading what you actually got

A constraint is a request; the track's settings are the result:

JavaScript
const [track] = stream.getVideoTracks();
console.log(track.getSettings());       // { width: 1280, height: 720, frameRate: 30, deviceId: '...' }
console.log(track.getCapabilities());   // { width: {min:1, max:1920}, ... }
console.log(track.getConstraints());    // what you asked for

getCapabilities() tells you the range the device supports, which is how you build a resolution picker that only offers real options.

Changing constraints while live

You do not need to reopen the camera to change resolution or frame rate. applyConstraints() adjusts the track in place:

applyConstraints on a live track

Notes: a canvas track can only be scaled down (the source is 640 by 360), and a failed applyConstraints leaves the old settings in place; it does not break the track.

Listing devices

JavaScript
await navigator.mediaDevices.getUserMedia({ audio: true, video: true }).then(s => s.getTracks().forEach(t => t.stop()));
const devices = await navigator.mediaDevices.enumerateDevices();
for (const d of devices) console.log(d.kind, d.label, d.deviceId);

Each entry has kind (videoinput, audioinput or audiooutput), label, deviceId and groupId (devices that belong to one physical unit, such as a headset's microphone and speaker).

Privacy rule: before the user has granted permission, labels are empty strings and deviceIds may be blank. After a getUserMedia grant you get real labels. That is why device pickers call getUserMedia first (even briefly) and then enumerate. Also listen for hot-plugging:

JavaScript
navigator.mediaDevices.addEventListener('devicechange', refreshDeviceList);

Choosing and switching a device

Pass the id as an exact constraint:

JavaScript
const stream = await navigator.mediaDevices.getUserMedia({
  video: { deviceId: { exact: selectedCameraId } },
});

To switch cameras during a call, open the new camera and replace the track on the sender instead of renegotiating:

JavaScript
const newStream = await navigator.mediaDevices.getUserMedia({ video: { deviceId: { exact: id } } });
const [newTrack] = newStream.getVideoTracks();
await videoSender.replaceTrack(newTrack);          // no new offer needed
oldTrack.stop();

replaceTrack is covered in transceivers and senders.

For speakers, audioElement.setSinkId(deviceId) routes playback to a chosen output (not supported in every browser).

Audio processing constraints

Three built-in processors are on by default for microphones:

Constraint What it does Turn off when
echoCancellation Removes the far end's voice picked up by your mic Music, headphones-only setups
noiseSuppression Reduces steady background noise Recording ambient sound or instruments
autoGainControl Evens out volume Studio-quality capture
JavaScript
const music = await navigator.mediaDevices.getUserMedia({
  audio: { echoCancellation: false, noiseSuppression: false, autoGainControl: false, channelCount: 2 },
});

Common mistakes

  • Using exact for width/height: breaks on phones. Use ideal.
  • Enumerating before permission: empty labels.
  • Forgetting to stop the old track after switching: the old camera stays on.
  • Requesting 1080p on weak devices and then wondering about CPU load: see video quality in the quality chapter.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens if an ideal constraint cannot be met?

    ideal is a preference. Only exact (and unsatisfiable min or max) cause an OverconstrainedError.
  2. 2. Why are device labels empty before permission is granted?

    Real labels and ids are only exposed after the user has granted access to capture.
  3. 3. How do you change a live track's resolution without reopening the camera?

    applyConstraints adjusts the existing track's settings in place.
  4. 4. Which approach switches cameras during a call without a new offer?

    replaceTrack swaps the media source on an existing sender and needs no renegotiation.

Summary

  • Constraints describe what you want: ideal for preferences, exact, min and max for requirements.
  • getSupportedConstraints(), getCapabilities() and getSettings() tell you what exists and what you got.
  • applyConstraints() changes a live track; enumerateDevices() lists inputs and outputs after permission is granted.
  • Switch devices with deviceId constraints plus replaceTrack().
  • Echo cancellation, noise suppression and gain control are on by default; turn them off for music.

Next: MediaStream and Tracks