WebRtc10: 端对端1v1传输基本流程

媒体能力协商过程

RTCPeerConnection(核心类)

  • 基本格式
    pc = new RTCPeerConnection([configiration]);

RTCPeerConnection方法分类

  • 媒体协商
  • Stream/Track
  • 传输相关方法
  • 统计相关方法

媒体协商过程

协商状态变化

媒体协商方法

  • createOffer
  • createAnswer
  • setLocalDescription
  • setRemoeteDescription

createOffer

  • 基本格式
    aPromise = myPeerConnection.createOffer([options]);

createAnswer

  • 基本格式
    aPromise = myPeerConnection.createAnswer([options]);

setLocalDescription

  • 基本格式
    aPromise = myPc.setLocalDescription(sessionDescription);

setRemoeteDescription

  • 基本格式
    aPromise = myPc.setRemoeteDescription(sessionDescription);

Track方法

  • addTrack
  • removeTrack

addTrack

  • 基本格式
    rtpSender = myPc.addTrack(track, stream...);
  • 参数
    track: 添加到RTCPeerConnection中的媒体轨
    stream:指定track所在的stream

removeTrack

  • 基本格式
    myPc.removeTrack(rtpSender);

重要事件

  • onnegotiationneeded
  • onicecandidate

1:1连接的基本流程

实战:本机内的1:1音视频互通

index.html

html 复制代码
<html>
    <head>
        <title>WebRTC PeerConnection</title>
    </head>
    <body>
        <div>
            <video id="localvideo" autoplay playsinline></video>
            <video id="remotevideo" autoplay playsinline></video>
            <div>
                <button id="start">Start</button>
                <button id="call">Call</button>
                <button id="hangup">HangUp</button>
            </div>
        </div>

        <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
        <script src="js/main.js"></script>
    </body>
</html>

main.js

js 复制代码
'use strict'

var localVideo = document.querySelector('video#localVideo');
var remoteVideo = document.querySelector('video#remoteVideo');
var btnStart = document.querySelector('button#start');
var btnCall = document.querySelector('button#call');
var btnHangUp= document.querySelector('button#hangup');


var localStream;
var pc1;
var pc2;

function gotMediaStream(stream){
	localVideo.srcObject = stream;
	localStream = stream;
}

function handleError(err){
	console.log("Failed to call getUserMedia", err);
}

function start(){
	var constraints = {
		video: true,
		audio: false 
	}

	if(!navigator.mediaDevices ||
		!navigator.mediaDevices.getUserMedia){
		return;
	}else {
		navigator.mediaDevices.getUserMedia(constraints)
					.then(gotMediaStream)
					.catch(handleError);
	}

}

function gotAnswerDescription(desc){
	pc2.setLocalDescription(desc);

	//send sdp to caller
	//recieve sdp from callee
	
	pc1.setRemoteDescription(desc);

}

function gotLocalDescription(desc){
	pc1.setLocalDescription(desc);

	//send sdp to callee
	
	//receive sdp from caller 
 	pc2.setRemoteDescription(desc);	
	pc2.createAnswer().then(gotAnswerDescription)
			 .catch(handleError);
}

function gotRemoteStream(e){

	if(remoteVideo.srcObject !== e.streams[0]){
		remoteVideo.srcObject = e.streams[0];
	}
}

function call(){
	var offerOptions = {
		offerToReceiveAudio: 0,
		offerToReceiveVideo: 1 
	}

	pc1 = new RTCPeerConnection();
	pc1.onicecandidate = (e) => {
	
		// send candidate to peer
		// receive candidate from peer

		pc2.addIceCandidate(e.candidate)
			.catch(handleError);
		console.log('pc1 ICE candidate:', e.candidate);
	}

	pc1.iceconnectionstatechange = (e) => {
		console.log(`pc1 ICE state: ${pc.iceConnectionState}`);
		console.log('ICE state change event: ', e);
	}


	pc2 = new RTCPeerConnection();
	pc2.onicecandidate = (e)=> {
	
		// send candidate to peer
		// receive candidate from peer

		pc1.addIceCandidate(e.candidate)
			.catch(handleError);
		console.log('pc2 ICE candidate:', e.candidate);
	}

	pc2.iceconnectionstatechange = (e) => {
		console.log(`pc2 ICE state: ${pc.iceConnectionState}`);
		console.log('ICE state change event: ', e);
	}

	pc2.ontrack = gotRemoteStream;

	//add Stream to caller
	localStream.getTracks().forEach((track)=>{
		pc1.addTrack(track, localStream);
	});

	pc1.createOffer(offerOptions)
		.then(gotLocalDescription)
		.catch(handleError);

}


function hangup(){
	pc1.close();
	pc2.close();
	pc1 = null;
	pc2 = null;

}

btnStart.onclick = start;
btnCall.onclick = call;
btnHangUp.onclick = hangup;
相关推荐
小陈爱建模2 天前
2025五一杯C题五一杯数学建模思路代码文章教学:社交媒体平台用户分析问题
数学建模·媒体
C灿灿数模2 天前
2025五一杯数学建模C题:社交媒体平台用户分析问题,完整第一问模型与求解+代码
数学建模·媒体
程序员Bears5 天前
深入理解CSS3:Flex/Grid布局、动画与媒体查询实战指南
前端·css3·媒体·visual studio code
云天徽上7 天前
【数据可视化-33】病毒式社交媒体潮流与用户参与度可视化分析
机器学习·信息可视化·数据挖掘·数据分析·媒体
财经汇报11 天前
媒体关注:联易融聚焦AI+业务,重塑供应链金融生态
人工智能·金融·媒体
北京阳光34811 天前
外商在国内宣传 活动|发布会|参展 邀请媒体
媒体
姚家湾11 天前
闲聊人工智能对媒体的影响
人工智能·媒体
mycm030411 天前
媒体发稿软文推广:新闻稿写什么内容
经验分享·媒体
1302520151211 天前
品牌如何通过朝日新闻出海日本?——某企业日本媒体发稿实战
媒体·日本媒体·海外媒体发稿·朝日新闻