可以使用瀏覽器打開手機端攝像頭

可以先後攝像頭切換,可以截取當前視頻流圖像javascript

兼容各大主流瀏覽器,java

主要使用的api:git

// 獲取視頻流
navigator.mediaDevices.getUserMedia(constrains).then(success).catch(error);

// 獲取設備攝像信息
navigator.mediaDevices.enumerateDevices().then(gotDevices).then(getStream).catch(handleError);

以前在本機上測試Chrome出現問題,問題在於沒有使用https做爲測試連接,若是使用http的話,則項目不能打開攝像頭,這可能與chrome的明文加密有關係github

若是使用http,代碼會報
NotSupportedError Only secure origins are allowed (see: https://goo.gl/Y0ZkNV)
可是這個錯開始並無報,開始我直接運行獲取視頻流代碼,項目的代碼彷彿中止運行通常,相應位置的console.log也沒有輸出,這個錯誤也沒有報
後來通過調試,獲取視頻流的代碼放在點擊事件中,錯誤纔出來。。web

切換攝像頭代碼:

// 多選框更改事件
videoSelect.onchange = getStream;

// 獲取設備音頻輸出設備與攝像設備,這裏我只用到了攝像設備
function gotDevices(deviceInfos) {
    console.log('deviceInfos')
    console.log('deviceInfos:', deviceInfos);
    for (let i = 0; i !== deviceInfos.length; i++) {
        let deviceInfo = deviceInfos[i];
        var option = document.createElement('option');
        // console.log(deviceInfo)
        if (deviceInfo.kind === 'videoinput') {  // audiooutput  , videoinput
            option.value = deviceInfo.deviceId;
            option.text = deviceInfo.label || 'camera ' + (videoSelect.length + 1);
              videoSelect.appendChild(option);
        }
    }
}

兼容瀏覽器:

//訪問用戶媒體設備的兼容方法
function getUserMedia(constrains,success,error){
    if(navigator.mediaDevices.getUserMedia){
        //最新標準API
        navigator.mediaDevices.getUserMedia(constrains).then(success).catch(error);
    } else if (navigator.webkitGetUserMedia){
        //webkit內核瀏覽器
        navigator.webkitGetUserMedia(constrains).then(success).catch(error);
    } else if (navigator.mozGetUserMedia){
        //Firefox瀏覽器
        navagator.mozGetUserMedia(constrains).then(success).catch(error);
    } else if (navigator.getUserMedia){
        //舊版API
        navigator.getUserMedia(constrains).then(success).catch(error);
    }
}

獲取視頻流成功回調:

function getStream(){

    if (window.stream) {
        window.stream.getTracks().forEach(function(track) {
            track.stop();
        })
    }

    if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia){
        //調用用戶媒體設備,訪問攝像頭
        const constraints = {
            audio: true, 
            video: {
                width: { ideal: 1280 },
                height: { ideal: 720 },
                frameRate: { 
                    ideal: 10,
                    max: 15
                },
                deviceId: {exact: videoSelect.value}
            }
        };
        console.log('獲取視頻流');
        getUserMedia(constraints,success,error);
    } else {
        alert("你的瀏覽器不支持訪問用戶媒體設備");
    }
}

截取視頻流做爲圖片:

//註冊拍照按鈕的單擊事件
document.getElementById("capture").addEventListener("click",function(){
    //繪製畫面
    console.log('點擊事件');
    context.drawImage(video,0,0,480,320);
});

源碼地址chrome

相關文章
相關標籤/搜索