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 = require('rtcpeerconnection');
var pc = new PeerConnection({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:
pc.on('ice', function (candidate) {
connection.send('ice', candidate);
});
pc.on('endOfCandidates', function () {
});
pc.on('addStream', function (event) {
});
pc.on('removeStream', function (event) {
});
pc.on('answer', function (err, answer) { ... });
pc.on('offer', function (err, offer) { ... });
pc.on('close', function () { ... });
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:
var pc = new PeerConnection(config, constraints);
var connection = new RealTimeConnection();
pc.offer(function (err, offer) {
if (!err) connection.send('offer', offer)
});
pc.offer(
{
offerToReceiveAudio: true,
offerToReceiveVideo: false
},
function (err, offer) {
if (!err) connection.send('offer', offer);
}
);
connection.on('offer', function (offer) {
pc.handleOffer(offer, function (err) {
if (err) {
return;
}
pc.answer(function (err, answer) {
if (!err) connection.send('answer', answer);
});
pc.answer(MY_CONSTRAINTS, function (err, answer) {
if (!err) connection.send('answer', answer);
});
pc.answerVideoOnly(function (err, answer) { ... });
pc.answerAudioOnly(function (err, answer) { ... });
});
});
connection.on('answer', function (answer) {
pc.handleAnswer(answer);
});
pc.on('ice', function (candidate) {
connection.send('ice', candidate);
});
connection.on('ice', function (candidate) {
pc.processIce(candidate);
});
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.