HTML Media Devices API

πŸ“± Introduction to the Media Devices API

The Media Devices API allows web applications to access connected media input devices like cameras, microphones, and screens. This API is essential for building apps with video calls, audio recording, or live streaming features. 🎀🎬

>>β€œCapture and stream the world directly from your browser!” πŸŒπŸ“Ή

πŸ“Œ What is the Media Devices API?

It’s a part of the WebRTC specification that enables access to media hardware via JavaScript, mainly through navigator.mediaDevices. It handles permissions, device enumeration, and streaming.

βš™οΈ Accessing User Camera and Microphone

Request permission and get a media stream like this:

Get User Media Example

navigator.mediaDevices.getUserMedia({ video: true, audio: true })
  .then(stream => {
    const videoElement = document.querySelector('video');
    videoElement.srcObject = stream;
    videoElement.play();
  })
  .catch(error => {
    console.error('Error accessing media devices:', error);
  });

πŸ“‹ Listing Available Media Devices

You can list all connected media devices (cameras, microphones, speakers):

Enumerate Media Devices

navigator.mediaDevices.enumerateDevices()
  .then(devices => {
    devices.forEach(device => {
      console.log(device.kind + ": " + device.label + " id = " + device.deviceId);
    });
  })
  .catch(error => {
    console.error('Error listing devices:', error);
  });

🧠 Handling Permissions

Browsers ask users for permission before granting access to media devices. Always handle permission denial gracefully in your app.

Note

⚠️ Make sure your site is served over HTTPS; getUserMedia only works in secure contexts.

🎞️ Example: Displaying Video Stream

HTML:

HTML Video Tag

<video autoplay playsinline></video>

JavaScript to stream camera feed into video element:

Code Snippet

navigator.mediaDevices.getUserMedia({ video: true })
  .then(stream => {
    const video = document.querySelector('video');
    video.srcObject = stream;
  })
  .catch(console.error);

🧩 Tips & Best Practices

  • Always check for navigator.mediaDevices support before using the API.
  • Stop tracks when done to free device resources: stream.getTracks().forEach(track => track.stop()).
  • Use constraints (like resolution or frame rate) to optimize performance.
  • Handle errors such as no device found or permission denied.

πŸ”— Useful Resources

>>β€œMedia Devices API bridges hardware and web for rich multimedia experiences.” 🎧πŸŽ₯