WebRTC的相关知识点可以参考 mdn介绍
- WebRTC API 获取音视频设备 常用的api有 enumerateDevices,getUserMedia,getDisplayMedia
WebRTC 提供了 mediaDevices.enumerateDevices API 来获取系统的音视频设备信息。
const ePromise = navigator.mediaDevices.enumerateDevices();
上述调用返回值是一个 Promise 对象,当完成时会返回一个 MediaDeviceInfo 对象 和 InputDeviceInfo对象组成的数组。
MediaDeviceInfo/InputDeviceInfo 属性值含义解释如下:
| 属性 | 含义 |
|---|---|
| deviceId | 设备 ID |
| label | 设备名称 |
| kind | 设备种类,如 audioinput/videoinput/audiooutput/videooutput |
| groupId | 设备组 ID |
实例如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WebRTC获取音视频设备</title>
</head>
<body>
<div>
<label>音频输入设备</label>
<select id="audio_input"></select>
</div>
<div>
<label>视频输入设备</label>
<select id="video_input"></select>
</div>
<div>
<label>音频输出设备</label>
<select id="audio_output"></select>
</div>
<script src="./js/enumerate_devices.js"></script>
</body>
</html>
var audioInput = document.querySelector("select#audio_input");
var videoInput = document.querySelector("select#video_input");
var audioOutput = document.querySelector("select#audio_output");
function HandleError(err) {
console.log(err.name + "," + err.message);
}
function GetStream(stream) {
return navigator.mediaDevices.enumerateDevices();
}
function GetDevices(deviceInfos) {
deviceInfos.forEach(function(deviceInfo) {
var option = document.createElement("option");
option.text = deviceInfo.label;
option.value = deviceInfo.deviceId;
if (deviceInfo.kind === "audioinput") {
audioInput.appendChild(option);
} else if (deviceInfo.kind === "videoinput") {
videoInput.appendChild(option);
} else if (deviceInfo.kind === "audiooutput") {
audioOutput.appendChild(option);
} else if (deviceInfo.kind === "videooutput") {
videoOutput.appendChild(option);
} else {
console.log("unknown device kind");
}
});
}
if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
console.log('enumerateDevices is not supported!');
} else {
navigator.mediaDevices.getUserMedia({audio: true, video: true})
.then(GetStream)
.then(GetDevices)
.catch(HandleError);
}