<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>div.select { margin: 0 0 1em 0; }</style>
</head>
<body>
<div class="select">
<label for="audioSource">Audio source: </label><select id="audioSource"></select>
</div>
<div class="select">
<label for="videoSource">Video source: </label><select id="videoSource"></select>
</div>
<video muted autoplay></video>
</body>
</html>
<script>
const videoElement = document.querySelector('video');
const audioSelect = document.querySelector('select#audioSource');
const videoSelect = document.querySelector('select#videoSource');
navigator.mediaDevices.enumerateDevices()
.then(gotDevices).then(getStream).catch(handleError);
audioSelect.onchange = getStream;
videoSelect.onchange = getStream;
function gotDevices(deviceInfos) {
for (var i = 0; i !== deviceInfos.length; ++i) {
var deviceInfo = deviceInfos[i];
var option = document.createElement('option');
option.value = deviceInfo.deviceId;
if (deviceInfo.kind === 'audioinput') {
option.text = deviceInfo.label ||
'microphone ' + (audioSelect.length + 1);
audioSelect.appendChild(option);
} else if (deviceInfo.kind === 'videoinput') {
option.text = deviceInfo.label || 'camera ' +
(videoSelect.length + 1);
videoSelect.appendChild(option);
} else {
console.log('Found one other kind of source/device: ', deviceInfo);
}
}
}
function getStream() {
if (window.stream) {
window.stream.getTracks().forEach(function(track) {
track.stop();
});
}
var constraints = {
audio: {
deviceId: {exact: audioSelect.value}
},
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.log('Error: ', error);
}
</script>
154300cookie-checkHTML Video / Microphone capture