最近发现我写的都是乱七八糟的,觉得应该给大家带点福利,于是写了这篇
背景:最近想做个web应用,需要用到摄像头,但是发现默认一直是前置摄像头,拍照很麻烦,于是找了很多文章,居然没有人提到,只好*去找外文,终于看到了HTML5的一些定义,研究以后……挺简单的,注意这句
MediaStreamTrack.getSources(gotSources);
有了这句就搞定了
html就不解释了,js里有一个兼容各个浏览器的
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
然后是获取设备,就是上面说的需要注意的这句……研究好久才知道是这么用的……
最后选择好设备后,绑定设备,刷新就好了 源码如下,敏感部分我修改掉了,不过这个应该可以运行的
<div>
<label for='audioSource'>Audio source: </label><select id='audioSource'></select>
<label for='videoSource'>Video source: </label><select id='videoSource'></select>
<video id="me" width="160" height="120" autoplay></video>
<video id="you" width="160" height="120" autoplay></video>
</div>
<script type="text/javascript">
var videoElement = document.querySelector("video#me");
var audioSelect = document.querySelector("select#audioSource");
var videoSelect = document.querySelector("select#videoSource");
var startButton = document.querySelector("button#start"); navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia || navigator.mozGetUserMedia; function gotSources(sourceInfos) {
for (var i = 0; i != sourceInfos.length; ++i) {
var sourceInfo = sourceInfos[i];
var option = document.createElement("option");
option.value = sourceInfo.id;
if (sourceInfo.kind === 'audio') {
option.text = sourceInfo.label || 'microphone ' + (audioSelect.length + 1);
audioSelect.appendChild(option);
} else if (sourceInfo.kind === 'video') {
option.text = sourceInfo.label || 'camera ' + (videoSelect.length + 1);
videoSelect.appendChild(option);
} else {
console.log('Some other kind of source: ', sourceInfo);
}
}
} if (typeof MediaStreamTrack === 'undefined') {
alert('This browser does not support MediaStreamTrack.\n\nTry Chrome Canary.');
} else {
MediaStreamTrack.getSources(gotSources);
} function successCallback(stream) {
window.stream = stream; // make stream available to console
videoElement.src = window.URL.createObjectURL(stream);
videoElement.play();
} function errorCallback(error) {
console.log("navigator.getUserMedia error: ", error);
} function start() {
if (!!window.stream) {
videoElement.src = null;
window.stream.stop();
}
var audioSource = audioSelect.value;
var videoSource = videoSelect.value;
var constraints = {
audio: {
optional: [{ sourceId: audioSource }]
},
video: {
optional: [{ sourceId: videoSource }]
}
};
navigator.getUserMedia(constraints, successCallback, errorCallback);
} audioSelect.onchange = start;
videoSelect.onchange = start; start();
</script>
不知道这里能显示不,可以选择当前设备的音频和视频,然后切换以后会实时体现的