WebRTC Between two pages in the same machine - javascript

I'm trying to implement a mechanism to send textual data (JSON for instance) in from page to page, using javascript at the same machine.
I found some code and wrapped it but it only works at the same page.
At the moment I don't want to use a WwebRTC framework, only adapter.js.
//Must include adapter.js before
var WebRTCManager = (function () {
'use strict';
//Ctor
function WebRTCManagerFn() {
console.log('WebRTCManagerFn ctor reached');
this._events = {};
this._localConnection = null
this._remoteConnection = null;
this._sendChannel = null;
this._receiveChannel = null;
}
WebRTCManagerFn.prototype.addEventListener = function (name, handler) {
if (this._events.hasOwnProperty(name))
this._events[name].push(handler);
else
this._events[name] = [handler];
};
WebRTCManagerFn.prototype._fireEvent = function (name, event) {
if (!this._events.hasOwnProperty(name))
return;
if (!event)
event = {};
var listeners = this._events[name], l = listeners.length;
for (var i = 0; i < l; i++) {
listeners[i].call(null, event);
}
};
WebRTCManagerFn.prototype.createConnection = function () {
var servers = null;
var pcConstraint = null;
var dataConstraint = null;
console.log('Using SCTP based data channels');
// SCTP is supported from Chrome 31 and is supported in FF.
// No need to pass DTLS constraint as it is on by default in Chrome 31.
// For SCTP, reliable and ordered is true by default.
// Add localConnection to global scope to make it visible
// from the browser console.
window.localConnection = this._localConnection =
new RTCPeerConnection(servers, pcConstraint);
console.log('Created local peer connection object localConnection');
this._sendChannel = this._localConnection.createDataChannel('sendDataChannel',
dataConstraint);
console.log('Created send data channel');
this._localConnection.onicecandidate = this._localIceCallback.bind(this);
this._sendChannel.onopen = this._onSendChannelStateChange.bind(this);
this._sendChannel.onclose = this._onSendChannelStateChange.bind(this);
// Add remoteConnection to global scope to make it visible
// from the browser console.
window.remoteConnection = this._remoteConnection =
new RTCPeerConnection(servers, pcConstraint);
console.log('Created remote peer connection object remoteConnection');
this._remoteConnection.onicecandidate = this._remoteIceCallback.bind(this);
this._remoteConnection.ondatachannel = this._receiveChannelCallback.bind(this);
this._localConnection.createOffer(this._gotOfferFromLocalConnection.bind(this), this._onCreateSessionDescriptionError.bind(this));
}
WebRTCManagerFn.prototype._onCreateSessionDescriptionError = function (error) {
console.log('Failed to create session description: ' + error.toString());
}
WebRTCManagerFn.prototype.sendMessage = function (msgText) {
var msg = new Message(msgText);
// Send the msg object as a JSON-formatted string.
var data = JSON.stringify(msg);
this._sendChannel.send(data);
console.log('Sent Data: ' + data);
}
WebRTCManagerFn.prototype.closeDataChannels = function () {
console.log('Closing data channels');
this._sendChannel.close();
console.log('Closed data channel with label: ' + this._sendChannel.label);
this._receiveChannel.close();
console.log('Closed data channel with label: ' + this._receiveChannel.label);
this._localConnection.close();
this._remoteConnection.close();
this._localConnection = null;
this._remoteConnection = null;
console.log('Closed peer connections');
}
WebRTCManagerFn.prototype._gotOfferFromLocalConnection = function (desc) {
console.log('reached _gotOfferFromLocalConnection');
if (this && this._localConnection != 'undefined' && this._remoteConnection != 'undefined') {
this._localConnection.setLocalDescription(desc);
console.log('Offer from localConnection \n' + desc.sdp);
this._remoteConnection.setRemoteDescription(desc);
this._remoteConnection.createAnswer(this._gotAnswerFromRemoteConnection.bind(this),
this._onCreateSessionDescriptionError.bind(this));
}
}
WebRTCManagerFn.prototype._gotAnswerFromRemoteConnection = function (desc) {
console.log('reached _gotAnswerFromRemoteConnection');
if (this && this._localConnection != 'undefined' && this._remoteConnection != 'undefined') {
this._remoteConnection.setLocalDescription(desc);
console.log('Answer from remoteConnection \n' + desc.sdp);
this._localConnection.setRemoteDescription(desc);
}
}
WebRTCManagerFn.prototype._localIceCallback = function (event) {
console.log('local ice callback');
if (event.candidate) {
this._remoteConnection.addIceCandidate(event.candidate,
this._onAddIceCandidateSuccess.bind(this), this._onAddIceCandidateError.bind(this));
console.log('Local ICE candidate: \n' + event.candidate.candidate);
}
}
WebRTCManagerFn.prototype._remoteIceCallback = function (event) {
console.log('remote ice callback');
if (event.candidate) {
this._localConnection.addIceCandidate(event.candidate,
this._onAddIceCandidateSuccess.bind(this), this._onAddIceCandidateError.bind(this));
console.log('Remote ICE candidate: \n ' + event.candidate.candidate);
}
}
WebRTCManagerFn.prototype._onAddIceCandidateSuccess = function (evt) {
debugger;
console.log('AddIceCandidate success. evt: '+ evt);
}
WebRTCManagerFn.prototype._onAddIceCandidateError = function (error) {
console.log('Failed to add Ice Candidate: ' + error.toString());
}
WebRTCManagerFn.prototype._receiveChannelCallback = function (event) {
console.log('Receive Channel Callback');
this._receiveChannel = event.channel;
this._receiveChannel.onmessage = this._onReceiveMessageCallback.bind(this);
this._receiveChannel.onopen = this._onReceiveChannelStateChange.bind(this);
this._receiveChannel.onclose = this._onReceiveChannelStateChange.bind(this);
}
WebRTCManagerFn.prototype._onReceiveMessageCallback = function (event) {
console.log('Received Message: ' + event.data);
console.log('Received Message this is: ' + this);
var msgObj = JSON.parse(event.data);
this._fireEvent("messageRecieved", {
details: {
msg: msgObj
}
});
}
WebRTCManagerFn.prototype._onSendChannelStateChange = function () {
console.log('_onSendChannelStateChange');
var readyState = this._sendChannel.readyState;
console.log('Send channel state is: ' + readyState);
}
WebRTCManagerFn.prototype._onReceiveChannelStateChange = function () {
var readyState = this._receiveChannel.readyState;
console.log('Receive channel state is: ' + readyState);
}
return WebRTCManagerFn;
})();
My question is how to pass data between two pages on the same machine using WebRTC?

This WebRTC tab chat demo works across tabs or windows in the same browser without a server: https://jsfiddle.net/f5y48hcd/ (I gave up making it work in a code snippet due to a SecurityError.)
Open the fiddle in two windows and try it out. For reference, here's the WebRTC code:
var pc = new RTCPeerConnection(), dc, enterPressed = e => e.keyCode == 13;
var connect = () => init(dc = pc.createDataChannel("chat"));
pc.ondatachannel = e => init(dc = e.channel);
var init = dc => {
dc.onopen = e => (dc.send("Hi!"), chat.select());
dc.onclose = e => log("Bye!");
dc.onmessage = e => log(e.data);
};
chat.onkeypress = e => {
if (!enterPressed(e)) return;
dc.send(chat.value);
log("> " + chat.value);
chat.value = "";
};
var sc = new localSocket(), send = obj => sc.send(JSON.stringify(obj));
var incoming = msg => msg.sdp &&
pc.setRemoteDescription(new RTCSessionDescription(msg.sdp))
.then(() => pc.signalingState == "stable" || pc.createAnswer()
.then(answer => pc.setLocalDescription(answer))
.then(() => send({ sdp: pc.localDescription })))
.catch(log) || msg.candidate &&
pc.addIceCandidate(new RTCIceCandidate(msg.candidate)).catch(log);
sc.onmessage = e => incoming(JSON.parse(e.data));
pc.oniceconnectionstatechange = e => log(pc.iceConnectionState);
pc.onicecandidate = e => send({ candidate: e.candidate });
pc.onnegotiationneeded = e => pc.createOffer()
.then(offer => pc.setLocalDescription(offer))
.then(() => send({ sdp: pc.localDescription }))
.catch(log);
var log = msg => div.innerHTML += "<br>" + msg;
I use this for demoing WebRTC data channels. Note that the secret sauce is the localSocket.js that I wrote for this, which looks like this:
function localSocket() {
localStorage.a = localStorage.b = JSON.stringify([]);
this.index = 0;
this.interval = setInterval(() => {
if (!this.in) {
if (!JSON.parse(localStorage.a).length) return;
this.in = "a"; this.out = "b";
}
var arr = JSON.parse(localStorage[this.in]);
if (arr.length <= this.index) return;
if (this.onmessage) this.onmessage({ data: arr[this.index] });
this.index++;
}, 200);
setTimeout(() => this.onopen && this.onopen({}));
}
localSocket.prototype = {
send: function(msg) {
if (!this.out) {
this.out = "a"; this.in = "b";
}
var arr = JSON.parse(localStorage[this.out]);
arr.push(msg);
localStorage[this.out] = JSON.stringify(arr);
},
close: function() {
clearInterval(this.interval);
}
};
It basically uses localStorage to simulate web sockets locally between two tabs. If this is all you want to do, then you don't even need WebRTC data channels.
Disclaimer: It's not very robust, and relies on two pages being ready to communicate, so not production-ready by any means.

Related

Send data whit WebSockets on C# and JS

I am trying to send data from c # to js with websockets, so they look for example send an alert when activating a function from C # but I can not make a successful connection to send and receive the data, this is my code js
var ws;
var reconnectTimer;
function connect() {
ws = new WebSocket('ws://' + host + ':' + port + '/');
ws.onopen = function() {
clearInterval(reconnectTimer);
console.log('Conexión WebSockets establecida');
};
ws.onmessage = function(e) {
if (!e.data || e.data.length === 0 || e.data === '')
return;
console.log('Recibiendo: ' + e.data);
var message = JSON.parse(e.data);
if (message.Name === undefined)
return;
if (!handlers.has(message.Name))
return;
if (message.Arguments === undefined)
message.Arguments = [];
handlers.get(message.Name)(ws, message.Arguments, message);
};
ws.onclose = function() {
console.log('Conexión WebSockets no establecida, esperando reconexión');
clearInterval(reconnectTimer);
reconnectTimer = setInterval(reconnect, 3000);
};
}
function reconnect() {
console.log('Reconectando WebSockets...');
ws.close();
ws = undefined;
connect();
}
connect();
function sendMessage(handlerName, args) {
var jsonMessage = {
Name: handlerName,
Arguments: args
};
var message = JSON.stringify(jsonMessage);
console.log('Enviando: ' + message);
ws.send(message);
}
I'm using "Fleck" in C#, but I can't get it to work.

Need Help Making Java Script Discord Music Bot

I have tried to use this code to make a discord music bot but i am getting error telling me i need ffmpeg, but how would I implement it into this code?
index.js file
const Discord = require('discord.js');
const bot = new Discord.Client();
const config = require("./config.json");
const ytdl = require('ytdl-core');
var youtube = require('./youtube.js');
var ytAudioQueue = [];
var dispatcher = null;
bot.on('message', function(message) {
var messageParts = message.content.split(' ');
var command = messageParts[0].toLowerCase();
var parameters = messageParts.splice(1, messageParts.length);
switch (command) {
case "-join" :
message.reply("Attempting to join channel " + parameters[0]);
JoinCommand(parameters[0], message);
break;
case "-play" :
PlayCommand(parameters.join(" "), message);
break;
case "-playqueue":
PlayQueueCommand(message);
break;
}
});
function PlayCommand(searchTerm) {
if(bot.voiceConnections.array().length == 0) {
var defaultVoiceChannel = bot.channels.find(val => val.type === 'voice').name;
JoinCommand(defaultVoiceChannel);
}
youtube.search(searchTerm, QueueYtAudioStream);
}
function PlayQueueCommand(message) {
var queueString = "";
for(var x = 0; x < ytAudioQueue.length; x++) {
queueString += ytAudioQueue[x].videoName + ", ";
}
queueString = queueString.substring(0, queueString.length - 2);
message.reply(queueString);
}
function JoinCommand(ChannelName) {
var voiceChannel = GetChannelByName(ChannelName);
if (voiceChannel) {
voiceChannel.join();
console.log("Joined " + voiceChannel.name);
}
return voiceChannel;
}
/* Helper Methods */
function GetChannelByName(name) {
var channel = bot.channels.find(val => val.name === name);
return channel;
}
function QueueYtAudioStream(videoId, videoName) {
var streamUrl = youtube.watchVideoUrl + videoId;
if (!ytAudioQueue.length) {
ytAudioQueue.push(
{
'streamUrl' : streamUrl,
'videoName' : videoName
}
);
console.log('Queued audio ' + videoName);
PlayStream(ytAudioQueue[0].streamUrl);
}
else {
ytAudioQueue.push(
{
'streamUrl' : streamUrl,
'videoName' : videoName
}
);
}
console.log("Queued audio " + videoName);
}
function PlayStream(streamUrl) {
const streamOptions = {seek: 0, volume: 1};
if (streamUrl) {
const stream = ytdl(streamUrl, {filter: 'audioonly'});
if (dispatcher == null) {
var voiceConnection = bot.voiceConnections.first();
if(voiceConnection) {
console.log("Now Playing " + ytAudioQueue[0].videoname);
dispatcher = bot.voiceConnections.first().playStream(stream, streamOptions);
dispatcher.on('end', () => {
dispatcher = null;
PlayNextStreamInQueue();
});
dispatcher.on('error', (err) => {
console.log(err);
});
}
} else {
dispatcher = bot.voiceConnections.first().playStream(stream, streamOptions);
}
}
}
function PlayNextStreamInQueue() {
ytAudioQueue.splice(0, 1);
if (ytAudioQueue.length != 0) {
console.log("now Playing " + ytAudioQueue[0].videoName);
PlayStream(ytAudioQueue[0].streamUrl);
}
}
bot.login(config.token);
youtube.js file
var request = require('superagent');
const API_KEY = "My API KEY";
const WATCH_VIDEO_URL = "https://www.youtube.com/watch?v=";
exports.watchVideoUrl = WATCH_VIDEO_URL;
exports.search = function search(searchKeywords, callback) {
var requestUrl = 'https://www.googleapis.com/youtube/v3/search' + '?part=snippet&q=' + escape(searchKeywords) + '&key=' + API_KEY;
request(requestUrl, (error, response) => {
if (!error && response.statusCode == 200) {
var body = response.body;
if (body.items.length == 0) {
console.log("I Could Not Find Anything!");
return;
}
for (var item of body.items) {
if (item.id.kind == 'youtube#video') {
callback(item.id.videoId, item.snippet.title);
return;
}
}
} else {
console.log("Unexpected error!");
return;
}
});
return;
};
Error I am getting when I try to run code :
Joined General
C:\Discord Bot\node_modules\discord.js\src\client\voice\pcm\FfmpegConverterEngine.
js:80
throw new Error(
^
Error: FFMPEG was not found on your system, so audio cannot be played. Please make
sure FFMPEG is installed and in your PATH.
You need to download/extract FFMPEG and make it as your PATH/System variable[environment variable]
Make sure that you have it as your System variable like this :
The System Variable should named as 'FFMPEG' and should be directed to where the execution(.exe) file is. It should be in a folder called 'bin' in your FFMPEG folder.
You can google/search online on how to add a new System/PATH variable for your specific OS.

How to start a basic WebRTC data channel?

How to start a basic WebRTC data channel?
This is what I have so far, but it doesn't even seem to try and connect. Im sure I am just missing something basic.
var RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection || window.msRTCPeerConnection;
var peerConnection = new RTCPeerConnection({
iceServers: [
{url: 'stun:stun1.l.google.com:19302'},
{url: 'stun:stun2.l.google.com:19302'},
{url: 'stun:stun3.l.google.com:19302'},
{url: 'stun:stun4.l.google.com:19302'},
]
});
peerConnection.ondatachannel = function () {
console.log('peerConnection.ondatachannel');
};
peerConnection.onicecandidate = function () {
console.log('peerConnection.onicecandidate');
};
var dataChannel = peerConnection.createDataChannel('myLabel', {
});
dataChannel.onerror = function (error) {
console.log('dataChannel.onerror');
};
dataChannel.onmessage = function (event) {
console.log('dataChannel.onmessage');
};
dataChannel.onopen = function () {
console.log('dataChannel.onopen');
dataChannel.send('Hello World!');
};
dataChannel.onclose = function () {
console.log('dataChannel.onclose');
};
console.log(peerConnection, dataChannel);
WebRTC assumes you have a way to signal (send an offer-string to, and receive an answer-string from) whomever you wish to contact. Without some server, how will you do that?
To illustrate, here's some code that does everything but that (works in Firefox and Chrome 45):
var config = { iceServers: [{ urls: "stun:stun.l.google.com:19302" }]};
var dc, pc = new RTCPeerConnection(config);
pc.ondatachannel = e => {
dc = e.channel;
dc.onopen = e => (log("Chat!"), chat.select());
dc.onmessage = e => log(e.data);
}
function createOffer() {
button.disabled = true;
pc.ondatachannel({ channel: pc.createDataChannel("chat") });
pc.createOffer().then(d => pc.setLocalDescription(d)).catch(failed);
pc.onicecandidate = e => {
if (e.candidate) return;
offer.value = pc.localDescription.sdp;
offer.select();
answer.placeholder = "Paste answer here";
};
};
offer.onkeypress = e => {
if (e.keyCode != 13 || pc.signalingState != "stable") return;
button.disabled = offer.disabled = true;
var obj = { type:"offer", sdp:offer.value };
pc.setRemoteDescription(new RTCSessionDescription(obj))
.then(() => pc.createAnswer()).then(d => pc.setLocalDescription(d))
.catch(failed);
pc.onicecandidate = e => {
if (e.candidate) return;
answer.focus();
answer.value = pc.localDescription.sdp;
answer.select();
};
};
answer.onkeypress = e => {
if (e.keyCode != 13 || pc.signalingState != "have-local-offer") return;
answer.disabled = true;
var obj = { type:"answer", sdp:answer.value };
pc.setRemoteDescription(new RTCSessionDescription(obj)).catch(failed);
};
chat.onkeypress = e => {
if (e.keyCode != 13) return;
dc.send(chat.value);
log(chat.value);
chat.value = "";
};
var log = msg => div.innerHTML += "<p>" + msg + "</p>";
var failed = e => log(e + ", line " + e.lineNumber);
<script src="https://rawgit.com/webrtc/adapter/master/adapter.js"></script>
<button id="button" onclick="createOffer()">Offer:</button>
<textarea id="offer" placeholder="Paste offer here"></textarea><br>
Answer: <textarea id="answer"></textarea><br><div id="div"></div>
Chat: <input id="chat"></input><br>
Open this page in a second tab, and you can chat from one tab to the other (or to a different machine around the world). What stinks is that you must get the offer there yourself:
Press the Offer button in Tab A (only) and wait 1-20 seconds till you see the offer-text,
copy-paste the offer-text from Tab A to Tab B, and hit Enter
copy-paste the answer-text that appears from Tab B to Tab A, and hit Enter.
You should now be able to chat between tabs, without a server.
As you can see, this is a sub-par experience, which is why you need some basic websocket server to pass offer/answer (as well as trickle ice candidates if you want connecting to happen fast) between A and B, to get things started. Once you have a connection, you can use data-channels for this, with a little extra work.

db value becomes null or even on indexdb open it does not go into onsuccess or upgradeneeded functions

(function () {
var db;
function openDB(dbname, dbtable, keypath) {
var version = 1;
// open the database
var indexeddb_request = indexedDB.open( dbname, version ); // connect + open database
// if error
indexeddb_request.onerror = function ( event ) {
console.log( event.target );
console.trace();
}
// if success
indexeddb_request.onsuccess = function ( event ) {
console.log( event.target );
console.trace();
db = event.target.result;
}
// if onupgradeneeded
indexeddb_request.onupgradeneeded = function( event ) {
console.log( event.target );
console.trace();
db = event.target.result;
var objectStore = db.createObjectStore( dbtable, { keyPath: 'url' } );
}
}
function getObjectStore(store_name, mode) {
var tx = db.transaction(store_name, mode);
return tx.objectStore(store_name);
}
function addPublication(dbtable, data) {
console.log("addPublication arguments:", arguments);
var store = getObjectStore(dbtable, 'readwrite');
var req;
try {
for (var i in data) {
req = store.add(data[i]);
}
//req = store.add(data);
} catch (e) {
if (e.name == 'DataCloneError')
displayActionFailure("This engine doesn't know how to clone a Blob, " +
"use Firefox");
throw e;
}
req.onsuccess = function (evt) {
console.log("Insertion in DB successful");
};
req.onerror = function() {
console.error("addPublication error", this.error);
};
}
function displayPubList(store, store_name) {
console.log("displayPubList");
if (typeof store == 'undefined')
store = getObjectStore(store_name, 'readonly');
var req;
req = store.count();
// Requests are executed in the order in which they were made against the
// transaction, and their results are returned in the same order.
// Thus the count text below will be displayed before the actual pub list
// (not that it is algorithmically important in this case).
req.onsuccess = function(evt) {
console.log("Count of records " + evt.target.result +
' record(s) in the object store.');
};
req.onerror = function(evt) {
console.error("add error", this.error);
};
var i = 0;
req = store.openCursor();
req.onsuccess = function(evt) {
var cursor = evt.target.result;
// If the cursor is pointing at something, ask for the data
if (cursor) {
console.log("displayPubList cursor:", cursor);
req = store.get(cursor.key);
req.onsuccess = function (evt) {
var value = evt.target.result;
console.log("Key :" + cursor.key + 'value :' + value.ssn );
};
// Move on to the next object in store
cursor.continue();
// This counter serves only to create distinct ids
i++;
} else {
console.log("No more entries");
}
};
}
openDB("abc","names","ssn");
const customerData = [
{ ssn: "444-44-4444", name: "Bill", age: 35, email: "bill#company.com" },
{ ssn: "555-55-5555", name: "Donna", age: 32, email: "donna#home.org" }
];
addPublication("names",customerData);
displayPubList("abc","names");
})();
I'm trying to test the above code from chrome developer tools. But looks like some cases the call goes into sucess or upgradeneeded. And many times its always null. Please let me know if i'm doing something wrong here.

Why this JavaScript event that does not start?

I'm trying to follow a tutorial on RTCPeerConnection API that enables the sharing of sound, image, data between browsers.
Here is the code that works:
function call() {
callButton.disabled = true;
hangupButton.disabled = false;
trace("Starting call");
if (localStream.getVideoTracks().length > 0) {
trace('Using video device: ' + localStream.getVideoTracks()[0].label);
}
if (localStream.getAudioTracks().length > 0) {
trace('Using audio device: ' + localStream.getAudioTracks()[0].label);
}
var servers = null;
localPeerConnection = new mozRTCPeerConnection(servers);
console.log(localPeerConnection);
trace("Created local peer connection object localPeerConnection");
localPeerConnection.onicecandidate = gotLocalIceCandidate;
remotePeerConnection = new mozRTCPeerConnection(servers);
trace("Created remote peer connection object remotePeerConnection");
remotePeerConnection.onicecandidate = gotRemoteIceCandidate;
remotePeerConnection.onaddstream = gotRemoteStream;
localPeerConnection.addStream(localStream);
trace("Added localStream to localPeerConnection");
localPeerConnection.createOffer(gotLocalDescription);
}
Here is my code that does not work:
Visio.prototype.call = function(visio){
callButton.disabled = true;
hangupButton.disabled = false;
console.log("Starting call...");
if (visio.localStream.getVideoTracks().length > 0) {
visio.trace('Using video device: ' + visio.localStream.getVideoTracks()[0].label);
}
if (visio.localStream.getAudioTracks().length > 0) {
visio.trace('Using audio device: ' + visio.localStream.getAudioTracks()[0].label);
}
var servers = null;
visio.localPeerConnection = new RTCPeerConnection(servers);
console.log(visio.localPeerConnection );
console.log("Created local peer connection object localPeerConnection");
visio.localPeerConnection.onicecandidate = visio.gotLocalIceCandidate;
visio.remotePeerConnection = new RTCPeerConnection(servers);
console.log("Created remote peer connection object remotePeerConnection");
visio.remotePeerConnection.onicecandidate = visio.gotRemoteIceCandidate;
visio.remotePeerConnection.onaddstream = visio.gotRemoteStream;
visio.localPeerConnection.addStream(visio.localStream);
console.log("Added localStream to localPeerConnection");
visio.localPeerConnection.createOffer(visio.gotLocalDescription);
};
with my call to the call method :
callButton.onclick = function(){that.call(that);};
As said in the title, the events : onicecandidate and onaddstream never triggered. I do not know why.
Any idea?
Ok , i modified my function. But it doesn't works anymore :(
This is the full code :
Visio.js
if(mozRTCPeerConnection){
RTCPeerConnection = mozRTCPeerConnection;
}else if(webkitRTCPeerConnection){
RTCPeerConnection = webkitRTCPeerConnection;
} else if(oRTCPeerConnection) {
RTCPeerConnection = oRTCPeerConnection;
} else {
alert("Votre navigateur ne supporte pas l'API RTCPeerConnection");
}
$(document).ready(function(){
new Visio();
});
function Visio() {
this.localStream, this.localPeerConnection, this.remotePeerConnection;
this.cam = new Cam();
//var localVideo = document.getElementById("localVideo");
var remoteVideo = document.getElementById("remoteVideo");
var startButton = document.getElementById("startButton");
var callButton = document.getElementById("callButton");
var hangupButton = document.getElementById("hangupButton");
startButton.disabled = false;
callButton.disabled = true;
hangupButton.disabled = true;
var that = this;
startButton.onclick = function(){that.start();};
callButton.onclick = function () { that.startCall(); };
hangupButton.onclick = function(){that.hangup();};
};
Visio.prototype.trace = function(text) {
console.log((performance.now() / 1000).toFixed(3) + ": " + text);
};
Visio.prototype.start = function(){
startButton.disabled = true;
this.cam.start();
//Waiting for stream.
var that = this;
var id = setInterval(function(){
console.log("Getting Stream...");
that.localStream = that.cam.stream;
if(that.localStream !== null){
console.log("Stream Ok!");
callButton.disabled = false;
clearInterval(id);
}
},500);
};
Visio.prototype.startCall = function () {
callButton.disabled = true;
hangupButton.disabled = false;
console.log("Starting call...");
if (this.localStream.getVideoTracks().length > 0) {
this.trace('Using video device: ' + this.localStream.getVideoTracks()[0].label);
}
if (this.localStream.getAudioTracks().length > 0) {
this.trace('Using audio device: ' + this.localStream.getAudioTracks()[0].label);
}
var servers = null;
this.localPeerConnection = new RTCPeerConnection(servers);
console.log("Created local peer connection object localPeerConnection");
this.localPeerConnection.onicecandidate = this.gotLocalIceCandidate;
this.remotePeerConnection = new RTCPeerConnection(servers);
console.log("Created remote peer connection object remotePeerConnection");
this.remotePeerConnection.onicecandidate = this.gotRemoteIceCandidate;
this.remotePeerConnection.onaddstream = this.gotRemoteStream;
this.localPeerConnection.addStream(this.localStream);
console.log("Added localStream to localPeerConnection");
this.localPeerConnection.createOffer(this.gotLocalDescription);
};
Visio.prototype.gotLocalDescription = function(description){
this.localPeerConnection.setLocalDescription(description);
console.log("Offer from localPeerConnection: \n" + description.sdp);
this.remotePeerConnection.setRemoteDescription(description);
this.remotePeerConnection.createAnswer(this.gotRemoteDescription);
};
Visio.prototype.gotRemoteDescription = function(description){
this.remotePeerConnection.setLocalDescription(description);
console.log("Answer from remotePeerConnection: \n" + description.sdp);
this.localPeerConnection.setRemoteDescription(description);
};
Visio.prototype.gotRemoteStream = function(event){
remoteVideo.src = URL.createObjectURL(event.stream);
trace("Received remote stream");
};
Visio.prototype.gotLocalIceCandidate = function(event){
if (event.candidate) {
remotePeerConnection.addIceCandidate(new RTCIceCandidate(event.candidate));
trace("Local ICE candidate: \n" + event.candidate.candidate);
}
};
Visio.prototype.gotRemoteIceCandidate = function(event){
if (event.candidate) {
localPeerConnection.addIceCandidate(new RTCIceCandidate(event.candidate));
trace("Remote ICE candidate: \n " + event.candidate.candidate);
}
};
Visio.prototype.hangup = function() {
console.log("Ending call");
this.localPeerConnection.close();
this.remotePeerConnection.close();
this.localPeerConnection = null;
this.remotePeerConnection = null;
hangupButton.disabled = true;
callButton.disabled = false;
};
And cam.js
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
function Cam(){
this.video = null;
this.stream = null;
navigator.getUserMedia ||
(navigator.getUserMedia = navigator.mozGetUserMedia ||
navigator.webkitGetUserMedia || navigator.msGetUserMedia);
if (!navigator.getUserMedia) {
alert('getUserMedia is not supported in this browser.');
}
};
Cam.prototype.start = function(){
var that = this;
navigator.getUserMedia({
video: true,
audio: true
}, function(stream){that.onSuccess(stream);}, that.onError);
};
Cam.prototype.stop = function(){
this.stopVideo();
this.stopSound();
};
Cam.prototype.startSound = function(){
};
Cam.prototype.stopSound = function(){
};
Cam.prototype.startVideo = function(){
};
Cam.prototype.stopVideo = function(){
};
Cam.prototype.onSuccess = function(stream){
var source = document.getElementById('localVideo');
var videoSource = null;
this.stream = stream;
if (window.webkitURL) {
videoSource = window.webkitURL.createObjectURL(stream);
} else {
videoSource = window.URL.createObjectURL(stream);
}
this.stream = stream;
source.autoplay = true;
source.src = videoSource;
this.video = source;
};
Cam.prototype.onError = function(err) {
alert('There has been a problem retrieving the streams - did you allow access?' + err);
};
Maybe it can help you :).
When you build a constructor function,
var Visio = function () {
// constructor
};
and add a prototype function,
Visio.prototype.startCall = function () {
// this === the new Visio object
};
you can use it like this:
var o = new Visio();
o.startCall();
Now inside your prototype function this is the object o instanceof Visio.
You are confusingly using the function name call. This name is also used by a Function.prototype.call function, with which you can override this.
Example:
Visio.prototype.myThisOverride = function () {
console.log(this);
};
Now when using Function.prototype.call, you see console log printing the string "Hello World", because this === 'Hello World':
var o = new Visio();
o.myThisOverride.call("Hello World");
So coming back to your code, you most likely have to rewrite it to:
Visio.prototype.startCall = function () {
callButton.disabled = true;
hangupButton.disabled = false;
console.log("Starting call...");
if (this.localStream.getVideoTracks().length > 0) {
this.trace('Using video device: ' + this.localStream.getVideoTracks()[0].label);
}
if (this.localStream.getAudioTracks().length > 0) {
this.trace('Using audio device: ' + this.localStream.getAudioTracks()[0].label);
}
var servers = null;
this.localPeerConnection = new RTCPeerConnection(servers);
console.log(this.localPeerConnection );
console.log("Created local peer connection object localPeerConnection");
this.localPeerConnection.onicecandidate = this.gotLocalIceCandidate;
this.remotePeerConnection = new RTCPeerConnection(servers);
console.log("Created remote peer connection object remotePeerConnection");
this.remotePeerConnection.onicecandidate = this.gotRemoteIceCandidate;
this.remotePeerConnection.onaddstream = this.gotRemoteStream;
this.localPeerConnection.addStream(this.localStream);
console.log("Added localStream to localPeerConnection");
this.localPeerConnection.createOffer(this.gotLocalDescription);
};
And use it like this:
var theVisio = new Visio();
callButton.onclick = function () { theVisio.startCall(); };
// which is the same as
callButton.onclick = function () { theVisio.startCall.call(theVisio); };
Or if you defined it like this inside the constructor:
var that = this;
callButton.onclick = function () { that.startCall(); };
// which is the same as
callButton.onclick = function () { that.startCall.call(that); };
And with this said, please respect the names call and apply because understanding operator this isn't the easiest thing in javaScript! ;)

Categories

Resources