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

咱们都知道 WebRTC 能够用来进行实时的音视频处理,那么第一步确定是要获取本地的音视频流,在 WebRTC 中获取本地的音视频流,须要用到 API:getUserMedia。html

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

建立工程

建立以下的工程:async

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

在 html 中添加 video

由于要显示视频,因此要在 html 中添加一个 video,以下:post

<!DOCTYPE html>
<html>

<body>

<div id="container">

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

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

</body>
</html>

复制代码

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

<!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>

复制代码

效果为:3d

给 showVideo 添加事件

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

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

async function init(e) {

}
复制代码

使用 getUserMedia

getUserMedia 的使用方式为:cdn

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 使用体验征文大赛 | 掘金技术征文,征文活动正在进行中

相关文章
相关标签/搜索