RTCPeerConnection
What is this?
A tiny browser module that normalizes and simplifies the API for WebRTC peer connections.
It gives us a cleaner (cross-browser) way to handle offer/answer and is based on an event emitter.
If you're not using browserify or you want AMD support use rtcpeerconnection.bundle.js
.
Installing
npm install rtcpeerconnection
How to use it
Instantiation
Instantiation takes the same options as a normal peer connection constructor:
var PeerConnection = ; // init it like a normal peer connection object// passing in ice servers/constraints the initial server config// also takes a couple other options:// debug: true (to log out all emitted events)var pc = config servers as usual constraints as to regular PC;
Events
Unlike stock Peer Connections this inherits from a generic event emitter. Powered by WildEmitter which has a very familiar API if you're used to node.js/jQuery/Backbone but also includes a wildcard handler so you can easily debug events. Just do emitter.on('*')
to log them out or whatnot.
But instead of doing pc.onicecandidate = function () {}
on a peer connection you listen for events like this:
// ice candidatespc; // you can listen for end of candidates (not particularly useful)pc; // remote stream addedpc; // remote stream removedpc; // you can chose to listen for events for // offers and answers instead, if you prefer pc;pc; // on peer connection closepc;
Methods
Note that all callbacks follow the "error first" convention. Meaning, rather than pass a success and fail callback, you pass a single callback.
If there is an error, the first argument passed to the callback will be a truthy value (the error itself).
The whole offer/answer cycle looks like this:
// assumptionsvar pc = config constraints;var connection = ; // could be socket.io or whatever // create an offerpc; // you can also optionally pass in constraints// when creating an offer.pc; // when you recieve an offer, you can answer// with various optionsconnection; // when you get an answer, you just call// handleAnswerconnection; // the only other thing you have to do is listen, transmit, and process ice candidates // you have to send them when generatedpc; // process incoming onesconnection;
That's it!
More
If you want higher level functionality look at SimpleWebRTC that uses this library.
License
MIT
Credits
If you like this, follow: @HenrikJoreteg on twitter.