目录

RTCPeerConnection基本概念-以及创建和绑定音视频以及渲染远端视频时候的作用

RTCPeerConnection基本概念 – 以及创建和绑定音视频以及渲染远端视频时候的作用

RTCPeerConnection 是WebRTC的核心的 是其暴露个用户的统一接口 其由多个模块组成

· 网络处理模块

· 服务质量模块

· 音视频引擎模块 等等

最最厉害的就是根据网络情况动态调整出音视频的最佳服务质量

创建RTCPeerConnection

配置ICE  也就是建立网络协商方式

var pcConfig = {
'iceServers': [{
'urls': 'turn:xxx.fun:3478',
'credential': "root",
'username': "root"
}]
};

pc = new RTCPeerConnection(pcConfig);

configuration 参数分析

bundlePolicy 指定如何绑定传输通道
banlanced:音频与视频轨使用各自的传输通道
max­compat:每个轨使用自己的传输通道
max­bundle:都绑定到同一个传输通道(主要使用)
iceTransportPolicy 指定 ICE 的传输策略
relay:只使用中继候选者 (测试时使用)
all:可以使用任何类型的候选者(一般使用)
iceServers 其由 RTCIceServer 组成,每个 RTCIceServer 都是一个 ICE 代理的服务器(如上 demo)
credential 凭据,只有 TURN 服务使用
credentialType 凭据类型,可以 password 或 oauth
urls 用于连接服中的 ur 数组
username 用户名,只有 TURN 服务使用
rtcpMuxPolicy rtcp 的复用策略,该选项在收集 ICE 候选者时使用
negotiate 收集 RTCP 与 RTP 复用的 ICE 候选者,如果 RTCP 能复用就与 RTP 复用,如果不能复用,就将他们单独使用
require 只能收集 RTCP 与 RTP 复用的 ICE 候选者,如果 RTCP 不能复用,则失败(一般使用)

绑定本本地流

function bindTracks(){

    console.log('bind tracks into RTCPeerConnection!');

    if( pc === null || pc === undefined) {
    	console.error('pc is null or undefined!');
    	return;
    }

    if(localStream === null || localStream === undefined) {
    	console.error('localstream is null or undefined!');
    	return;
    }

    //add all track into peer connection
    localStream.getTracks().forEach((track)=>{
    	pc.addTrack(track, localStream);
    });

}

function getMediaStream(stream){

    if(localStream){
    	stream.getAudioTracks().forEach((track)=>{
    		localStream.addTrack(track);
    		stream.removeTrack(track);
    	});
    }else{
    	localStream = stream;
    }

    localVideo.srcObject = localStream;

    //这个函数的位置特别重要,
    //一定要放到getMediaStream之后再调用
    //否则就会出现绑定失败的情况

    conn();

}

远端音视频渲染

每当远端的音视频数据传递过来的时候 RTCPeerConnection 对象的 Ontrack()事件就会触发

我们只需要给其设置一个回调函数即可

 pc = new RTCPeerConnection(pcConfig);

        pc.onicecandidate = (e)=>{

            if(e.candidate) {
                sendMessage(roomid, {
                    type: 'candidate',
                    label:event.candidate.sdpMLineIndex,
                    id:event.candidate.sdpMid,
                    candidate: event.candidate.candidate
                });
            }else{
                console.log('this is the end candidate');
            }
        }

        pc.ontrack = getRemoteStream;

function getRemoteStream(e){
remoteStream = e.streams[0];
remoteVideo.srcObject = e.streams[0];
}