WebRTC 使用之 —— 使用 getUserMedia 获取视频流 | 掘金技术征文

3,997 阅读2分钟

我们都知道 WebRTC 可以用来进行实时的音视频处理,那么第一步肯定是要获取本地的音视频流,在 WebRTC 中获取本地的音视频流,需要用到 API:getUserMedia。

本节教程就叫你如何使用 getUserMedia 来获取本地的音视频流。

创建工程

创建如下的工程:

一个 index.html + 一个main.js。

在 html 中添加 video

因为要显示视频,所以要在 html 中添加一个 video,如下:

<!DOCTYPE html>
<html>

<body>

<div id="container">

    <video id="gum-local" autoplay playsinline></video>
</div>

<script src="js/main.js"></script>

</body>
</html>

然后在加一个 showVideo 的按钮,意思是按了这个按钮之后,在调用摄像头显示视频,代码如下:

<!DOCTYPE html>

<html>

<body>

<div id="container">

    <video id="gum-local" autoplay playsinline></video>
    <button id="showVideo">Open camera</button>

</div>

<script src="js/main.js"></script>

</body>
</html>

效果为:

给 showVideo 添加事件

下来在 main.js 里添加代码,首先是获取 showVideo 的按钮,为其添加点击的事件监听:

document.querySelector('#showVideo').addEventListener('click', e => init(e));

async function init(e) {

}

使用 getUserMedia

getUserMedia 的使用方式为:

navigator.mediaDevices.getUserMedia(constraints);

需要传入 constraints 参数,constraints 参数可以控制是否开启视频和音频,如下:

const constraints = window.constraints = {
  audio: true,
  video: true
};

所以在 init() 方法里就可以这么写:

async function init(e) {
  const constraints = window.constraints = {
    audio: true,
    video: true
  };
  
  try {
    const stream = await navigator.mediaDevices.getUserMedia(constraints);
    handleSuccess(stream);
    e.target.disabled = true;
  } catch (e) {
    handleError(e);
  }
}

handleSuccess() 和 handleError() 为:

function handleSuccess(stream) {
  const video = document.querySelector('video');
  const videoTracks = stream.getVideoTracks();
  console.log('Got stream with constraints:', constraints);
  console.log(`Using video device: ${videoTracks[0].label}`);
  window.stream = stream; // make variable available to browser console
  video.srcObject = stream;
}

function handleError(error) {
  console.error(error);
}

点击 Open camera 后,首先会弹出授权框:

点击 Allow 后,就可以看到视频了:

Agora SDK 使用体验征文大赛 | 掘金技术征文,征文活动正在进行中