WebRTC use of - use RTCPeerConnection establish a video connection | Nuggets technology essay

The following examples will demonstrate how to create a connection using WebRTC video of RTCPeerConnection API.

Create Project

Create the following projects:

A index.html + a main.js.

Add video in html

In index.html, add two video, and are localVideo remoteVideo, for establishing an analog video connection ends.

Creating three buttons: Start, Call, Hang Up, used to simulate the operation of the process of establishing the video:

Start: localVideo open the camera and display video

Call: localVideo request to remoteVideo, and displays the video remoteVideo

Hang Up: remoteVideo hang up

So index.html code is:

<!DOCTYPE html>

<html>

<body>

<div id="container">

    <video id="localVideo" playsinline autoplay muted></video>
    <video id="remoteVideo" playsinline autoplay></video>

    <div class="box">
        <button id="startButton">Start</button>
        <button id="callButton">Call</button>
        <button id="hangupButton">Hang Up</button>
    </div>

</div>

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

</body>
</html>
复制代码

Displays the following effects:

After Index.html in the realization of the layout, begin to implement specific functions in main.js years.

Start function realization

Start function to achieve localVideo open the camera and display video.

This time getUserMedia need to use this API.

code show as below:

let localStream;
const startButton = document.getElementById('startButton');
startButton.addEventListener('click', start);

async function start() {
  console.log('Requesting local stream');
  startButton.disabled = true;
  try {
    const stream = await navigator.mediaDevices.getUserMedia({audio: true, video: true});
    console.log('Received local stream');
    localVideo.srcObject = stream;
    localStream = stream;
    callButton.disabled = false;
  } catch (e) {
    alert(`getUserMedia() error: ${e.name}`);
  }
}
复制代码

Just click Start, will show the current video on a web page, as follows:

![image-20190603030244840](/Users/koude/Library/Application Support/typora-user-images/image-20190603030244840.png)

Call function realization

Call function to achieve localVideo a request to the remoteVideo, and displays the video remoteVideo.

Call function is a core function, will establish a connection for the video ends, RTCPeerConnection need to use this API.

First get localVideo and remoteVideo two Video, and create two variables to represent these two Video of PeerConnection, localVideo as pc1, remoteVideo to pc2:

const localVideo = document.getElementById('localVideo');
const remoteVideo = document.getElementById('remoteVideo');

let pc1;
let pc2;
复制代码

Then get the Call button, and assign the click event:

const callButton = document.getElementById('callButton');
callButton.addEventListener('click', call);
async function call() {
}
复制代码

In the call () which is necessary to establish a connection using the RTCPeerConnection, a is pc1, a is pc1, and then establish a connection to pc1 pc2:

async function call() {
  callButton.disabled = true;
  hangupButton.disabled = false;
  console.log('Starting call');
  caches
  pc1 = new RTCPeerConnection();
  console.log('Created local peer connection object pc1');
  pc1.addEventListener('icecandidate', e => onIceCandidate(pc1, e));
  pc2 = new RTCPeerConnection({});
  console.log('Created remote peer connection object pc2');
  pc2.addEventListener('icecandidate', e => onIceCandidate(pc2, e));
  pc2.addEventListener('track', gotRemoteStream);

  localStream.getTracks().forEach(track => pc1.addTrack(track, localStream));
  console.log('Added local stream to pc1');

  try {
    console.log('pc1 createOffer start');
    const offer = await pc1.createOffer(offerOptions);
    await onCreateOfferSuccess(offer);
  } catch (e) {
  }
}

async function onCreateOfferSuccess(desc) {
  console.log(`Offer from pc1\n${desc.sdp}`);
  console.log('pc1 setLocalDescription start');
  try {
    await pc1.setLocalDescription(desc);
  } catch (e) {
  }

  console.log('pc2 setRemoteDescription start');
  try {
    await pc2.setRemoteDescription(desc);
  } catch (e) {
  }

  console.log('pc2 createAnswer start');
  // Since the 'remote' side has no media stream we need
  // to pass in the right constraints in order for it to
  // accept the incoming offer of audio and video.
  try {
    const answer = await pc2.createAnswer();
    await onCreateAnswerSuccess(answer);
  } catch (e) {
  }
}


function gotRemoteStream(e) {
  if (remoteVideo.srcObject !== e.streams[0]) {
    remoteVideo.srcObject = e.streams[0];
    console.log('pc2 received remote stream');
  }
}

async function onCreateAnswerSuccess(desc) {
  console.log(`Answer from pc2:\n${desc.sdp}`);
  console.log('pc2 setLocalDescription start');
  try {
    await pc2.setLocalDescription(desc);
  } catch (e) {
  }
  console.log('pc1 setRemoteDescription start');
  try {
    await pc1.setRemoteDescription(desc);
  } catch (e) {
  }
}

async function onIceCandidate(pc, event) {
  try {
    await (getOtherPc(pc).addIceCandidate(event.candidate));
  } catch (e) {
  }
}

const offerOptions = {
  offerToReceiveAudio: 1,
  offerToReceiveVideo: 1
};

function getName(pc) {
  return (pc === pc1) ? 'pc1' : 'pc2';
}

function getOtherPc(pc) {
  return (pc === pc1) ? pc2 : pc1;
}
复制代码

At this point, just click Call, will establish a connection, because this video is used the same computer, so the picture is as follows:

Hang Up function realization

Hang Up feature to achieve functional remoteVideo hang up the video connection. Properly achieved, as long as the closed pc1 and pc2 connection line, as follows:

const hangupButton = document.getElementById('hangupButton');
hangupButton.addEventListener('click', hangup);


function hangup() {
  console.log('Ending call');
  pc1.close();
  pc2.close();
  pc1 = null;
  pc2 = null;
  hangupButton.disabled = true;
  callButton.disabled = false;
}
复制代码

Hang Up screen after clicking below:

to sum up

Thus a simple video connectivity WebRTC of RTCPeerConnection API implementation to achieve complete.

Agora SDK experience essay contest | Nuggets technology essay writing, essay writing activities in progress

Reproduced in: https: //juejin.im/post/5cf4b397f265da1bbb03c4e4

Guess you like

Origin blog.csdn.net/weixin_33690367/article/details/91417397