WebRTC如何获取音频视频设备

enumerateDevices的使用

说明

enumerateDevices :获取音视频设备

基本格式

var ePromise = navigator.mediaDevices.enumerateDevices();

MediaDevicesInfo(返回的结构体):

JavaScript中的Promise

案例获取终端设备

vim index.html

<html>
  <head>
        <title> WebRTC 获取音视频设备</title>
  </head>
  <body>
    <div>
      <div>
        <label>audio input device:</label>
        <select id="audioSource"></select>
      </div>
      <div>
        <label>audio output device:</label>
        <select id="audioOutput"></select>
      </div>
      <div>
        <label>video input device:</label>
        <select id="videoSource"></select>
      </div>
    </div>
    <script src="./js/client.js"></script>
  </body>
</html>

vim client.js

"use strict"
// 获取js中的文件
var audioSource = document.querySelector("select#audioSource");
var audioOutput = document.querySelector("select#audioOutput");
var videoSource = document.querySelector("select#videoSource");


// 如果浏览器不支持音视频设备就直接退出
if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices){
  console.log("enumerateDevices is not supported!");
  
}else{
  navigator.mediaDevices.enumerateDevices()
  .then(gotDevices)
  .catch(handleError);
}

// 打印每一个设置的信息
function gotDevices(deviceInfos){
    deviceInfos.forEach(function(deviceInfo){
      console.log(deviceInfo.kind + ": label"             
                  + deviceInfo.label + ":id= "
                    + deviceInfo.deviceId + ":  groupId = "
                  + deviceInfo.groupId
                 );
      // 判断类型进行写入对应的选择框里面
      var option = document.createElement("option");
      option.text = deviceInfo.label;
      option.value = deviceInfo.deviceId;
      if(deviceInfo.kind === "audiosource"){
        audioSource.appendChild(option);
      }else if(deviceInfo.kind === "audiooutput"){
        audioOutput.appendChild(option);
      }else if(deviceInfo.kind === "videosource"){
        videoSource.appendChild(option);
      }
    });
}

// 打印出错信息
function handleError(err){
    console.log(err.name + ":" + err.message);
}

猜你喜欢

转载自www.cnblogs.com/fandx/p/12142313.html