webrtc学习——RTCPeerConnection

The RTCPeerConnection interface represents a WebRTC connection and handles efficient streaming of data between two peers.

Warning: RTCPeerConnection and RTCSessionDescription are currently prefixed in most browsers. You should include a polyfill if you‘re using it in any work. For instance:

var PeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
var SessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription || window.webkitRTCSessionDescription;
var GET_USER_MEDIA = navigator.getUserMedia ? "getUserMedia" :
                     navigator.mozGetUserMedia ? "mozGetUserMedia" :
                     navigator.webkitGetUserMedia ? "webkitGetUserMedia" : "getUserMedia";
var v = document.createElement("video");
var SRC_OBJECT = ‘srcObject‘ in v ? "srcObject" :
                 ‘mozSrcObject‘ in v ? "mozSrcObject" :
                 ‘webkitSrcObject‘ in v ? "webkitSrcObject" : "srcObject";

Basic Usage

Basic RTCPeerConnection usage involves negotiating a connection between your local machine and a remote one by generating Session Description Protocol to exchange between the two. i.e. The caller sends an offer. The called party responds with an answer. Both parties, the caller and the called party, need to set up their own RTCPeerConnection objects initially:

var pc = new RTCPeerConnection();
pc.onaddstream = function(obj) {
  var vid = document.createElement("video");
  document.appendChild(vid);
  vid.srcObject = obj.stream;
}

// Helper functions
function endCall() {
  var videos = document.getElementsByTagName("video");
  for (var i = 0; i < videos.length; i++) {
    videos[i].pause();
  }

  pc.close();
}

function error(err) { endCall(); }

Initializing the call

If you are the one initiating the initial connection you would call:

// Get a list of friends from a server
// User selects a friend to start a peer connection with
navigator.getUserMedia({video: true}, function(stream) {
  pc.onaddstream({stream: stream});
  // Adding a local stream won‘t trigger the onaddstream callback
  pc.addStream(stream);

  pc.createOffer(function(offer) {
    pc.setLocalDescription(new RTCSessionDescription(offer), function() {
      // send the offer to a server to be forwarded to the friend you‘re calling.
    }, error);
  }, error);
}

Answering a call

On the opposite end, the friend will receive the offer from the server.

var offer = getOfferFromFriend();
navigator.getUserMedia({video: true}, function(stream) {
  pc.onaddstream({stream: stream});
  pc.addStream(stream);

  pc.setRemoteDescription(new RTCSessionDescription(offer), function() {
    pc.createAnswer(function(answer) {
      pc.setLocalDescription(new RTCSessionDescription(answer), function() {
        // send the answer to a server to be forwarded back to the caller (you)
      }, error);
    }, error);
  }, error);
}

Handling the answer

Back on the original machine, you‘ll receive the response, and set it as the remote connection

// pc was set up earlier when we made the original offer
var offer = getResponseFromFriend();
pc.setRemoteDescription(new RTCSessionDescription(offer), function() { }, error);
 

Properties

This interface inherits properties from its parent element, EventTarget.

RTCPeerConnection.iceConnectionState Read only
Returns an enum of type RTCIceConnectionState that describes the ICE connection state for the connection. When this value changes, a iceconnectionstatechange event is fired on the object. The possible values are:

  • "new": the ICE agent is gathering addresses or waiting for remote candidates (or both).
  • "checking": the ICE agent has remote candidates, on at least one component, and is check them, though it has not found a connection yet. At the same time, it may still be gathering candidates.
  • "connected": the ICE agent has found a usable connection for each component, but is still testing more remote candidates for a better connection. At the same time, it may still be gathering candidates.
  • "completed": the ICE agent has found a usable connection for each component, and is no more testing remote candidates.
  • "failed": the ICE agent has checked all the remote candidates and didn‘t find a match for at least one component. Connections may have been found for some components.
  • "disconnected": liveness check has failed for at least one component. This may be a transient state, e. g. on a flaky network, that can recover by itself.
  • "closed": the ICE agent has shutdown and is not answering to requests.
RTCPeerConnection.iceGatheringState Read only
Returns an enum of type RTCIceGatheringState that describes the ICE gathering state for the connection. The possible values are:

  • "new": the object was just created, and no networking has occurred yet.
  • "gathering": the ICE engine is in the process of gathering candidates for this connection.
  • "complete": the ICE engine has completed gathering. Events such as adding a new interface or a new TURN server will cause the state to go back to gathering.
RTCPeerConnection.localDescription Read only
Returns a RTCSessionDescription describing the session for the local end of the connection. If it has not yet been set, it can be null.
RTCPeerConnection.peerIdentity Read only
Returns a RTCIdentityAssertion, that is a couple of a domain name (idp) and a name (name) representing the identity of the remote peer of this connection, once set and verified. If no peer has yet been set and verified, this property will return null. Once set, via the appropriate method, it can‘t be changed.
RTCPeerConnection.remoteDescription Read only
Returns a RTCSessionDescription describing the session for the remote end of the connection. If it has not yet been set, it can be null.
RTCPeerConnection.signalingState Read only
Returns an enum of type RTCSignalingState that describes the signaling state of the local connection. This state describes the SDP offer, that defines the configuration of the connections like the description of the locally associated objects of type MediaStream, the codec/RTP/RTCP options, the candidates gathered by the ICE Agent. When this value changes, a signalingstatechange event is fired on the object. The possible values are:

  • "stable": there is no SDP offer/answer exchange in progress. This is also the initial state of the connection.
  • "have-local-offer": the local end of the connection has locally applied a SDP offer.
  • "have-remote-offer": the remote end of the connection has locally applied a SDP offer.
  • "have-local-pranswer": a remote SDP offer has been applied, and a SDP pranswer applied locally.
  • "have-remote-pranswer": a local SDP offer has been applied, and a SDP pranswer applied remotely.
  • "closed": the connection is closed.

Event handlers

RTCPeerConnection.onaddstream
Is the event handler called when the addstream event is received. Such an event is sent when aMediaStream is added to this connection by the remote peer. The event is sent immediately after the call RTCPeerConnection.setRemoteDescription() and doesn‘t wait for the result of the SDP negotiation.
该动作是由对端的RTCpeerconnection的addstream动作产生的事件触发。
RTCPeerConnection.ondatachannel
Is the event handler called when the datachannel event is received. Such an event is sent when aRTCDataChannel is added to this connection.
RTCPeerConnection.onicecandidate
Is the event handler called when the icecandidate event is received. Such an event is sent when aRTCICECandidate object is added to the script.
RTCPeerConnection.oniceconnectionstatechange
Is the event handler called when the iceconnectionstatechange event is received. Such an event is sent when the value of iceConnectionState changes.
RTCPeerConnection.onidentityresult
Is the event handler called when the identityresult event is received. Such an event is sent when an identity assertion is generated, via getIdentityAssertion(), or during the creation of an offer or an answer.
RTCPeerConnection.onidpassertionerror
Is the event handler called when the idpassertionerror event is received. Such an event is sent when the associated identity provider (IdP) encounters an error while generating an identity assertion.
RTCPeerConnection.onidpvalidationerror
Is the event handler alled when the idpvalidationerror event is received. Such an event is sent when the associated identity provider (IdP) encounters an error while validating an identity assertion.
RTCPeerConnection.onnegotiationneeded
Is the event handler called when the negotiationneeded event, sent by the browser to inform that negotiation will be required at some point in the future, is received.
RTCPeerConnection.onpeeridentity
Is the event handler called when the peeridentity event, sent when a peer identity has been set and verified on this connection, is received.
RTCPeerConnection.onremovestream
Is the event handler called when the removestream event, sent when a MediaStream is removed from this connection, is received.
RTCPeerConnection.onsignalingstatechange
Is the event handler called when the signalingstatechange event, sent when the value ofsignalingState changes, is received.

Methods

RTCPeerConnection()
 
RTCPeerConnection.createOffer()
Creates an offer that is a request to find a remote peer with a specific configuration. The two first parameters of this methods are respectively success and error callbacks, the optional third one are options the user want to have, like audio or video streams.
RTCPeerConnection.createAnswer()
Creates an answer to the offer received by the remote peer, in a two-part offer/answer negotiation of a connection. The two first parameters are respectively success and error callbacks, the optional third one represent options for the answer to be created.
RTCPeerConnection.setLocalDescription()
Changes the local description associated with the connection. The description defines the properties of the connection like its codec. The connection is affected by this change and must be able to support both old and new descriptions. The method takes three parameters, aRTCSessionDescription object to set, and two callbacks, one called if the change of description succeeds, another called if it failed.
RTCPeerConnection.setRemoteDescription()
Changes the remote description associated with the connection. The description defines the properties of the connection like its codec. The connection is affected by this change and must be able to support both old and new descriptions. The method takes three parameters, aRTCSessionDescription object to set, and two callbacks, one called if the change of description succeeds, another called if it failed.
RTCPeerConnection.updateIce()
 
RTCPeerConnection.addIceCandidate()
 
RTCPeerConnection.getConfiguration()
 
RTCPeerConnection.getLocalStreams()
Returns an array of MediaStream associated with the local end of the connection. The array may be empty.
RTCPeerConnection.getRemoteStreams()
Returns an array of MediaStream associated with the remote end of the connection. The array may be empty.
RTCPeerConnection.getStreamById()
Returns the MediaStream with the given id that is associated with local or remote end of the connection. If no stream matches, it returns null.
RTCPeerConnection.addStream()
Adds a MediaStream as a local source of audio or video. If the negotiation already happened, a new one will be needed for the remote peer to be able to use it.
RTCPeerConnection.removeStream()
Removes a MediaStream as a local source of audio or video. If the negotiation already happened, a new one will be needed for the remote peer to stop using it.
RTCPeerConnection.close()
Abruptly closes a connection.
RTCPeerConnection.createDataChannel()
Creates a new RTCDataChannel associated with this connection. The method takes a dictionary as parameter, with the configuration required for the underlying data channel, like its reliability.
RTCPeerConnection.createDTMFSender()
Creates a new RTCDTMFSender, associated to a specific MediaStreamTrack, that will be able to sendDTMF phone signaling over the connection.
RTCPeerConnection.getStats()
Creates a new RTCStatsReport that contains and allows access to statistics regarding the connection.
RTCPeerConnection.setIdentityProvider()
Sets the Identity Provider (IdP) to the triplet given in parameter: its name, the protocol used to communicate with it (optional) and an optional username. The IdP will be used only when an assertion will be needed.
RTCPeerConnection.getIdentityAssertion()
Initiates the gathering of an identity assertion. This has an effect only if the signalingState is not"closed". It is not expected for the application dealing with the RTCPeerConnection: this is automatically done; an explicit call only allows to anticipate the need.

Constructor

new RTCPeerConnection(RTCConfiguration configuration, optional MediaConstraints constraints);

Note: While the PeerConnection specification reads like passing an RTCConfiguration object is required, Firefox will supply a default if you don‘t.

Methods

createOffer

void createOffer(RTCSessionDescriptionCallback successCallback,RTCPeerConnectionErrorCallback failureCallback, optional MediaConstraintsconstraints);

Create offer generates a blob of description data to facilitate a PeerConnection to the local machine. Use this when you‘ve got a remote Peer connection and you want to set up the local one.

Example

var pc = new PeerConnection();
pc.addStream(video);
pc.createOffer(function(desc){
  pc.setLocalDescription(desc, function() {
    // send the offer to a server that can negotiate with a remote client
  });
}

Arguments

successCallback
An RTCSessionDescriptionCallback which will be passed a single RTCSessionDescription object
errorCallback
An RTCPeerConnectionErrorCallback which will be passed a single DOMError object
[optional] constraints
An optional MediaConstraints object.

createAnswer

void createAnswer(RTCSessionDescriptionCallback successCallback,RTCPeerConnectionErrorCallback failureCallback, optional MediaConstraintsconstraints)")

Respond to an offer sent from a remote connection.

Example

var pc = new PeerConnection();
pc.setRemoteDescription(new RTCSessionDescription(offer), function() {
  pc.createAnswer(function(answer) {
    pc.setLocalDescription(answer, function() {
      // send the answer to the remote connection
    })
  })
});

Arguments

successCallback
An RTCSessionDescriptionCallback which will be passed a single RTCSessionDescription object
errorCallback
An RTCPeerConnectionErrorCallback which will be passed a single DOMError object
[optional] constraints
An optional MediaConstraints object.

updateIce()

updateIce(optional RTCConfiguration configuration, optional MediaConstraints constraints)

The updateIce method updates the ICE Agent process of gathering local candidates and pinging remote candidates. If there is a mandatory constraint called "IceTransports" it will control how the ICE engine can act. This can be used to limit the use to TURN candidates by a callee to avoid leaking location information prior to the call being accepted. This call may result in a change to the state of the ICE Agent, and may result in a change to media state if it results in connectivity being established.

Example

addIceCandidate()

addIceCandidate (RTCIceCandidate candidate, Function successCallback,RTCPeerConnectionErrorCallback failureCallback);

The addIceCandidate() method provides a remote candidate to the ICE Agent. In addition to being added to the remote description, connectivity checks will be sent to the new candidates as long as the "IceTransports" constraint is not set to "none". This call will result in a change to the connection state of the ICE Agent, and may result in a change to media state if it results in different connectivity being established.

Example

pc.addIceCandidate(new RTCIceCandidate(candidate));

createDataChannel

RTCDataChannel createDataChannel (DOMString label, optional RTCDataChannelInitdataChannelDict);

Creates a data channel for sending non video or audio data across the peer connection

Example

var pc = new PeerConnection();
var channel = pc.createDataChannel("Mydata");
channel.onopen = function(event) {
  channel.send(‘sending a message‘);
}
channel.onmessage = function(event) { console.log(event.data); }
时间: 2024-10-28 21:36:46

webrtc学习——RTCPeerConnection的相关文章

WebRTC学习笔记_Demo收集

1.     WebRTC学习 1.1   WebRTC现状 本人最早接触WebRTC是在2011年底,那时Google已经在Android源代码中添?了webrtc源代码,放在/external/webrtc/,可是Android并没实用到它,更没有被浏览器使用.当时试图在Android 2.3(Gingerbread)高通平台的手机上用H.264 硬件codec替换掉WebRTC缺省使用的VP8软codec,费了不少劲勉强换掉后效果非常差仅仅得放弃. 近期得知Google最新版的Chrome

WebRTC学习之九:摄像头的捕捉和显示

较新的WebRTC源码中已经没有了与VoiceEngine结构对应的VidoeEngine了,取而代之的是MeidaEngine.MediaEngine包含了MediaEngineInterface接口及其实现CompositeMediaEngine,CompositeMediaEngine本身也是个模板类,两个模板参数分别是音频引擎和视频引擎.CompositeMediaEngine派生类WebRtcMediaEngine依赖的模板参数是WebRtcVoiceEngine和WebRtcVide

webrtc学习(一): webrtc开始

一. 编译webrtc 1. 预先准备 1)  vpn. 用于同步代码. 这里给一个大概的估计吧. windows端包含vs2013 win8sdk wdk chromium源码等等, 总共需要至少8G. android端还需要android ndk sdk以及大量的依赖库, 大致也是10G往上. 所以需要网速不好的话, 同步一天也是很正常. 2. 同步代码及编译 http://www.webrtc.org/reference/getting-started 参考这个链接, 很详细, 需要认真看

webrtc学习: 部署stun和turn服务器

webrtc的P2P穿透部分是由libjingle实现的. 步骤顺序大概是这样的: 1. 尝试直连. 2. 通过stun服务器进行穿透 3. 无法穿透则通过turn服务器中转. stun 服务器比较简单. 网上也有很多公开的stun服务器可以用于测试. 例如 stun.ideasip.com 这里需要注意一下. 我在做android应用时. 在少数老旧的手机上出现过一个bug: PeerConnection close时非常慢. 大概需要50~80s. 后来反复检查, 才发现问题出在公用的stu

webrtc学习(二): audio_device之opensles

audio_device是webrtc的音频设备模块.  封装了各个平台的音频设备相关的代码 audio device 在android下封装了两套音频代码. 1. 通过jni调用java的media进行操作. 2. 直接通过opensl es的native c接口进行操作. native 接口自然比较高效,  但缺点在于opensl 要求 android 2.3+. OpenSL ES (Open Sound Library for Embedded Systems) 是无授权费.跨平台.针对

webrtc 学习资源1

1,http://www.webrtc.org/  webrtc官网,神马编译,神马下载,这里的解决方案才是最权威的. --------------------------------- 2,https://code.google.com/p/webrtc/  webrtc源码下载地点,您还可以随时随地关注最新修改. ---------------------------------- 3,https://webrtchacks.com/ 里面都是分享webrtc相关技术的文章 --------

webrtc学习———记录一

最近导师让研究一下webrtc,希望将来用到我们的ICT2系统中. 但是从来没有过做web的基础,无论前端还是后端,html.js全都从头学起.html还好说,没有太过复杂的东西. js就有点难度了,大致翻了一下js权威指南的书,了解了一下基本的语法,也算足够应付.但是对其中浏览器内置的各种对象,完全不了解. 只能慢慢熟悉,一步一步来. 第一部分 获取webcamera 这个比较简单,主要使用了getUserMedia()这个函数.下面是从网上获取的资料: 1.navigator.getUser

webrtc学习笔记1(建立连接基本流程)

最近在做一个基于webrtc的视频软件,以下是自己对于上层建立通话连接流程的基本理解,记录于此. 假设A和B要建立视频通话,A为房间创建端,B为加入房间端: 1.A通过http登录.获取其他服务器地址(做一些保存用户信息的操作,获取信令.stun.turn服务器地址等,非必要) 2.A和信令服务器建立websocket长连接 3.A通过websocket向信令服务器注册(创建房间,记录房间号,等待B加入房间) 4.A创建本地视频,获取A的sdp信息 5.B创建本地视频,获取B的sdp信息 6.B

WebRTC学习之 Intel&#174; Collaboration Suite for WebRTC源码流程解读

年后回来,因为新项目的需求,开始了解WebRTC相关的知识.目前接触的是Intel? Collaboration Suite for WebRTC.刚开始看SDK发现很多概念是我目前不知道的,于是恶补了一周基本的网络相关的知识.再来看Demo和Jar包里面的源码,对其代码逻辑的理解更深一步了.下面从代码层面分模块对Demo的设计和使用进行总结: 首先声明一下核心的类对象: private ConferenceClient mRoom; 无论是登录还是发布.订阅Stream,我们都需要mRoom来