最近發現我寫的都是亂七八糟的,覺得應該給大家帶點福利,於是寫了這篇
背景:最近想做個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>
不知道這里能顯示不,可以選擇當前設備的音頻和視頻,然后切換以后會實時體現的