Access Media Devices Javascript
Access All Media Devices available using JavaScript
by maheshBongani
HTML
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<video autoplay></video>
<select></select>
<button id="capture">Capture</button>
<canvas id="canvas" width=320 height=240></canvas>
<script>
</script>
</body>
</html>
JavaScript
const videoElement = document.querySelector('video');
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
const captureButton = document.getElementById('capture');
const videoSelect = document.querySelector('select');
navigator.mediaDevices.enumerateDevices()
.then(gotDevices).then(getStream).catch(handleError);
videoSelect.onchange = getStream;
function gotDevices(deviceInfos) {
for (let i = 0; i !== deviceInfos.length; ++i) {
const deviceInfo = deviceInfos[i];
console.log(deviceInfo);
const option = document.createElement('option');
option.value = deviceInfo.deviceId;
if (deviceInfo.kind === 'videoinput') {
console.log(deviceInfo);
option.text = deviceInfo.label || 'camera ' +
(videoSelect.length + 1);
videoSelect.appendChild(option);
} else {
console.log('Found another kind of device: ', deviceInfo);
}
}
}
function getStream() {
if (window.stream) {
window.stream.getTracks().forEach(function(track) {
track.stop();
});
}
const constraints = {
video: {
deviceId: {exact: videoSelect.value}
}
};
navigator.mediaDevices.getUserMedia(constraints).
then(gotStream).catch(handleError);
}
function gotStream(stream) {
window.stream = stream; // make stream available to console
videoElement.srcObject = stream;
}
function handleError(error) {
console.error('Error: ', error);
}
captureButton.addEventListener('click', () => {
// Draw the video frame to the canvas.
context.drawImage(videoElement, 0, 0, canvas.width, canvas.height);
var img = canvas.toDataURL("image/png");
document.write('<img src="'+img+'"/>');
// Stop all video streams.
videoElement.srcObject.getVideoTracks().forEach(track...