在之前我們已經學會了利用enumerateDevices這個API來獲取到音視頻設備,但是我們遇到了一個問題,如何在chrome瀏覽器中是可以看到音視頻設備的名字的,但是在safari瀏覽器中卻都是空白的。
在chrome下
在safari下名稱都是空的
這個原因非常簡單,就是因爲沒有獲取到相應的權限,由於各個瀏覽器它的實現是完全不一樣的,所以它對這個權限的控制也是不同的,那對於safari和FireFOX來說對權限的控制更嚴格一些,在chrome下也和不同的版本有關,那麼如何去解決這個問題呢?
這就要求我們在採集音視頻數據的時候,這個時候瀏覽器就會彈出一個窗口問你是否允許訪問音視頻設備,我們允許採集音視頻設備了,這樣我們就獲得了相應的訪問設備的權利,拿到這個權限之後,我們再去調用enumerateDevices,這個時候我們就可以拿到所有的設備名稱了。
下面我們來實踐一下,看是否能獲得設備名稱
index.html
<html>
<head>
<title>捕獲音視頻數據 WebRTC capture video and audio</title>
</head>
<body>
<div>
<label>audio Source:</label>
<select id="audioSource"></select>
</div>
<div>
<label>audio Output:</label>
<select id="audioOutput"></select>
</div>
<div>
<label>video Source:</label>
<select id="videoSource"></select>
</div>
<!--
我們創建一個video標籤,這個標籤就可以顯示我們捕獲的音視頻數據
autoplay 表示當我們拿到視頻源的時候直接播放
playsinlin 表示在瀏覽器頁面中播放而不是調用第三方工具
-->
<video autoplay playsinlin id="player"></video>
<!-- 引入 adapter.js庫 來做 不同瀏覽器的兼容 -->
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<script src="./js/client.js"></script>
</body>
</html>
client.js
'use strict'
var audioSource = document.querySelector('select#audioSource');
var audioOutput = document.querySelector('select#audioOutput');
var videoSource = document.querySelector('select#videoSource');
// 獲取video標籤
var videoplay = document.querySelector('video#player');
// deviceInfos是設備信息的數組
function gotDevices(deviceInfos){
// 遍歷設備信息數組, 函數裏面也有個參數是每一項的deviceinfo, 這樣我們就拿到每個設備的信息了
deviceInfos.forEach(function(deviceinfo){
// 創建每一項
var option = document.createElement('option');
option.text = deviceinfo.label;
option.value = deviceinfo.deviceId;
if(deviceinfo.kind === 'audioinput'){ // 音頻輸入
audioSource.appendChild(option);
}else if(deviceinfo.kind === 'audiooutput'){ // 音頻輸出
audioOutput.appendChild(option);
}else if(deviceinfo.kind === 'videoinput'){ // 視頻輸入
videoSource.appendChild(option);
}
})
}
// 獲取到流做什麼, 在gotMediaStream方面裏面我們要傳人一個參數,也就是流,
// 這個流裏面實際上包含了音頻軌和視頻軌,因爲我們通過constraints設置了要採集視頻和音頻
// 我們直接吧這個流賦值給HTML中賦值的video標籤
// 當時拿到這個流了,說明用戶已經同意去訪問音視頻設備了
function gotMediaStream(stream){
videoplay.srcObject = stream; // 指定數據源來自stream,這樣視頻標籤採集到這個數據之後就可以將視頻和音頻播放出來
// 當我們採集到音視頻的數據之後,我們返回一個Promise
return navigator.mediaDevices.enumerateDevices();
}
function handleError(err){
console.log('getUserMedia error:', err);
}
// 判斷瀏覽器是否支持
if(!navigator.mediaDevices ||
!navigator.mediaDevices.getUserMedia){
console.log('getUserMedia is not supported!');
}else{
var constraints = { // 表示同時採集視頻金和音頻
video : true,
audio : false
}
navigator.mediaDevices.getUserMedia(constraints)
.then(gotMediaStream) // 使用Promise串聯的方式,獲取流成功了
.then(gotDevices)
.catch(handleError);
}