webrtc学习——RTCPeerConnection
The RTCPeerConnection interface represents a WebRTC connection and handles efficient streaming of data between two peers.
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.iceConnectionStateRead only- Returns an enum of type
RTCIceConnectionStatethat describes the ICE connection state for the connection. When this value changes, aiceconnectionstatechangeevent 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.iceGatheringStateRead only- Returns an enum of type
RTCIceGatheringStatethat 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.localDescriptionRead only- Returns a
RTCSessionDescriptiondescribing the session for the local end of the connection. If it has not yet been set, it can benull. RTCPeerConnection.peerIdentityRead 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 returnnull. Once set, via the appropriate method, it can't be changed. RTCPeerConnection.remoteDescriptionRead only- Returns a
RTCSessionDescriptiondescribing the session for the remote end of the connection. If it has not yet been set, it can benull. RTCPeerConnection.signalingStateRead only- Returns an enum of type
RTCSignalingStatethat 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 typeMediaStream, the codec/RTP/RTCP options, the candidates gathered by the ICE Agent. When this value changes, asignalingstatechangeevent 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
addstreamevent is received. Such an event is sent when aMediaStreamis added to this connection by the remote peer. The event is sent immediately after the callRTCPeerConnection.setRemoteDescription()and doesn't wait for the result of the SDP negotiation. - 该动作是由对端的RTCpeerconnection的addstream动作产生的事件触发。
RTCPeerConnection.ondatachannel- Is the event handler called when the
datachannelevent is received. Such an event is sent when aRTCDataChannelis added to this connection. RTCPeerConnection.onicecandidate- Is the event handler called when the
icecandidateevent is received. Such an event is sent when aRTCICECandidateobject is added to the script. - 当脚本有新的RTCIceCandidate加入时,就会发送事件,并触发该函数。
RTCPeerConnection.oniceconnectionstatechange- Is the event handler called when the
iceconnectionstatechangeevent is received. Such an event is sent when the value oficeConnectionStatechanges. RTCPeerConnection.onidentityresult- Is the event handler called when the
identityresultevent is received. Such an event is sent when an identity assertion is generated, viagetIdentityAssertion(), or during the creation of an offer or an answer. RTCPeerConnection.onidpassertionerror- Is the event handler called when the
idpassertionerrorevent 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
idpvalidationerrorevent 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
negotiationneededevent, 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
peeridentityevent, sent when a peer identity has been set and verified on this connection, is received. RTCPeerConnection.onremovestream- Is the event handler called when the
removestreamevent, sent when aMediaStreamis removed from this connection, is received. RTCPeerConnection.onsignalingstatechange- Is the event handler called when the
signalingstatechangeevent, sent when the value ofsignalingStatechanges, 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, a
RTCSessionDescriptionobject 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, a
RTCSessionDescriptionobject 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
MediaStreamassociated with the local end of the connection. The array may be empty. RTCPeerConnection.getRemoteStreams()- Returns an array of
MediaStreamassociated with the remote end of the connection. The array may be empty. RTCPeerConnection.getStreamById()- Returns the
MediaStreamwith the given id that is associated with local or remote end of the connection. If no stream matches, it returnsnull. RTCPeerConnection.addStream()- Adds a
MediaStreamas 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
MediaStreamas 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
RTCDataChannelassociated 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 specificMediaStreamTrack, that will be able to sendDTMF phone signaling over the connection. RTCPeerConnection.getStats()- Creates a new
RTCStatsReportthat 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
signalingStateis not"closed". It is not expected for the application dealing with theRTCPeerConnection: 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
RTCSessionDescriptionCallbackwhich will be passed a singleRTCSessionDescriptionobject - errorCallback
- An
RTCPeerConnectionErrorCallbackwhich will be passed a singleDOMErrorobject - [optional] constraints
- An optional
MediaConstraintsobject.
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
RTCSessionDescriptionCallbackwhich will be passed a singleRTCSessionDescriptionobject - errorCallback
- An
RTCPeerConnectionErrorCallbackwhich will be passed a singleDOMErrorobject - [optional] constraints
- An optional
MediaConstraintsobject.
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); }
webrtc学习——RTCPeerConnection的更多相关文章
- webrtc学习———记录三:mediaStreamTrack
参考: https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack 转自http://c.tieba.baidu.com/p/3 ...
- WebRTC学习笔记_Demo收集
1. WebRTC学习 1.1 WebRTC现状 本人最早接触WebRTC是在2011年底,那时Google已经在Android源代码中增加了webrtc源代码,放在/external/w ...
- WebRTC学习
1. WebRTC学习 1.1 WebRTC现状 本人最早接触WebRTC是在2011年底,那时Google已经在Android源码中加入了webrtc源码,放在/external/web ...
- WebRTC学习与DEMO资源一览
一. WebRTC学习 1.1 WebRTC现状 本人最早接触WebRTC是在2011年底,那时Google已经在Android源码中加入了webrtc源码,放在/external/webrtc/ ...
- [转]webrtc学习: 部署stun和turn服务器
[转]webrtc学习: 部署stun和turn服务器 http://www.cnblogs.com/lingdhox/p/4209659.html webrtc的P2P穿透部分是由libjingle ...
- WebRTC学习之九:摄像头的捕捉和显示
较新的WebRTC源代码中已经没有了与VoiceEngine结构相应的VidoeEngine了,取而代之的是MeidaEngine.MediaEngine包括了MediaEngineInterface ...
- WebRTC的RTCPeerConnection()原理探析
从getUserMedia()到RTCPeerConnection(),自认为难度陡增.我想一方面是之前在Linux平台上学习ROS调用摄像头时,对底层的外设接口调用.摄像头参数都有学习理解:另一方面 ...
- WebRTC学习资料大全
在学习WebRTC,找了些资料,记录一下,供以后查询. 有些需要FQ才能看 WebRTC 介绍 官网在这里:https://webrtc.org/.然后这里有一个官方的Getting Started: ...
- WebRTC 学习之 概念总结
在学习WebRTC的时候,接触到了好多新的概念,在这里做一下备忘吧 RTMP协议 Real Time Messaging Protocol(实时消息传输协议).该协议基于TCP,是一个协议族,包括RT ...
随机推荐
- android WebViewClient的方法解释
1.在点击请求的是链接是才会调用,重写此方法返回true表明点击网页里面的链接还是在当前的webview里跳转,不跳到浏览器那边. public boolean shouldOverrideUrlLo ...
- oracle执行.sql文件
->win+R; ->CMD; ->SQLPLUS /NOLOG; ->CONNECT USER/PASSWORD@ORCL; ->@D:/XXX.SQL;
- 【原】1.1RDD源码解读(一)
1.RDD(Resilient Distributed DataSet)是Spark生态系统中最基本的抽象,代表不可变的.可并行操作的分区元素集合.RDD这个类有RDD系列所有基本的操作,比如map. ...
- AABB碰撞盒
矩形边界框(转) 另一种常见的用来界定物体的几何图元是矩形边界框,矩形边界框可以是与轴对齐的或是任意方向的.轴对齐矩形边界框有一个限制,就是它的边必须垂直于坐标轴.缩写AABB常用来表示axially ...
- 三种情形容易引起Azure虚拟机重新启动
与虚拟机或云服务角色中运行的代码有关的问题可能会导致重新启动.但是,Microsoft 在以下情况下也会重新启动您的角色: 来宾操作系统更新 – 仅影响云服务 Web 和辅助角色.有关如何限制这些 ...
- HDU-4419 Colourful Rectangle 矩形多面积并
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4419 利用二进制,R为1.G为2.B为4,然后通过异或运算可以得到其它组合颜色.建立7颗线段树,每颗线 ...
- ubuntu下使用脚本交叉编译windows下使用的ffmpeg + X264
这里主要是补充一些遇到的问题和解决方法. 2013-06 下旬 由于项目需要,重新编译ffmpeg+264+其他. 这里使用的环境Ubuntu 13.04,脚本依然是cross_compile_ffm ...
- Go Slices: usage and internals
Introduction Go's slice type provides a convenient and efficient means of working with sequences of ...
- javascript原型和原型继承
每一个javascript对象(null除外)都和原型对象相关联,每一个对象都从原型对象继承属性. 所有通过对象直接量创建的对象都具有同一个原型对象,并可以通过javascript代码Object.p ...
- 8-14-Exercise
8-14-小练 这次是我这组出题......我出的是B.C.D[虽然本来是想出的很难......╮(╯▽╰)╭但是,没找到AC1000+同时又让我想出的难题......SO...我出的真的不难= =] ...