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 使用體驗徵文大賽 | 掘金技術徵文,徵文活動正在進行中

相關文章
相關標籤/搜索