<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<main>
<div class="controls">
<button id="button">Get camera</button>
<select id="select"><option></option></select>
</div>
<video id="video" autoplay playsinline></video>
</main>
<script type="text/javascript">
const video = document.getElementById('video');
const button = document.getElementById('button');
const select = document.getElementById('select');
let currentStream;
function stopMediaTracks(stream) {
stream.getTracks().forEach(track => {
track.stop();
});
}
function gotDevices(mediaDevices) {
select.innerHTML = '';
select.appendChild(document.createElement('option'));
let count = 1;
mediaDevices.forEach(mediaDevice => {
if (mediaDevice.kind === 'videoinput') {
const option = document.createElement('option');
option.value = mediaDevice.deviceId;
const label = mediaDevice.label || `Camera ${count++}`;
const textNode = document.createTextNode(label);
option.appendChild(textNode);
select.appendChild(option);
}
});
}
button.addEventListener('click', event => {
if (typeof currentStream !== 'undefined') {
stopMediaTracks(currentStream);
}
const videoConstraints = {};
if (select.value === '') {
videoConstraints.facingMode = 'environment';
} else {
videoConstraints.deviceId = { exact: select.value };
}
const constraints = {
video: videoConstraints,
audio: false
};
navigator.mediaDevices
.getUserMedia(constraints)
.then(stream => {
currentStream = stream;
video.srcObject = stream;
return navigator.mediaDevices.enumerateDevices();
})
.then(gotDevices)
.catch(error => {
console.error(error);
});
});
navigator.mediaDevices.enumerateDevices().then(gotDevices);
</script>
</body>
</html>
参考地址:https://philnash.github.io/mediadevices-camera-selection/