π± 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. π€π¬
π 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
ποΈ 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.