Why I can't display remote stream? - webrtc

I want to make Alice in navig.html able to call Seb in index.html with a live video stream.
But in the index.html file, I am not able to display the remote live stream of Alice in index.html file because the video player displays nothing. Why ?
This is Alice, she has an offer (navig.html)
<video id="video1" controls ></video>
<script>
navigator.getUserMedia({audio:true, video:true}, success, error);
function success(stream) {
var video1 = document.querySelector("#video1");
video1.src = URL.createObjectURL(stream)
video1.play()
//rtcpeer
console.log("1")
var pc1 = new RTCPeerConnection()
pc1.addStream(stream)
pc1.createOffer().then(function(desc) {
pc1.setLocalDescription(desc)
console.log("" + JSON.stringify(desc))
})
}
function error(err) {
console.log(err)
}
</script>
This is Seb, he wants to receive live stream from Alice using its offer (index.html)
<video id="video1" controls ></video>
<textarea></textarea>
<p onclick="finir()">Fini</p>
<script>
function finir() {
navigator.getUserMedia({audio:true, video:true}, success, error);
}
function success(stream) {
var champ = document.querySelector("textarea").value
var texto = JSON.parse(champ)
console.log(texto)
var vid2 = document.querySelector("#video1");
var pc2 = new RTCPeerConnection()
pc2.setRemoteDescription(texto)
pc2.createAnswer()
pc2.onaddstream = function(e) {
vid2.src = URL.createObjectURL(e.stream);
vid2.play()
}
}
function error(err) {
console.log(err)
}
</script>
Thanks for helping

Oh, if it would be so simple ;).
With WebRTC you also need some kind of signaling protocol to exchange offer/answer between the parties. Please check one of the many WebRTC samples available.

Related

Mediastream Recording API. ondataavailable is not triggered

I am trying to record media using the mediaRecorder API. Here is my code (just the relevant part). I expect to get a console log in saveChunks but it appears that the ondataavailable event is never triggered.I am able to see the video in the video element.
recordedChunks = [];
navigator.mediaDevices.getUserMedia({video:true, audio:true})
.then(function(stream) {
myVideoMedia = document.getElementById("vid1");
myVideoMedia.srcObject = stream;
myVideoMedia.onloadedmetadata = function(e) {
myVideoMedia.play();
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.ondataavailable = saveChunks;
mediaRecorder.start();
console.log(mediaRecorder);
};
})
function saveChunks(event) {
console.log("Data recorded...");
//...
};
}
The console log of mediaRecorder.state is 'recording'
I did try by passing a timeslice of 1000 to start() and its working now! If no timeslice is passed, the function is called once at the end.

WebRTC No function was found that matched the signature provided

I tried this code:
<html>
<head>
</head>
<body>
<video src="" id="video1"></video>
<video src="" id="video2"></video>
<textarea id="lesdp"></textarea><p id="btn">Activer</p>
</body>
<script>
navigator.getUserMedia({audio:true,video:true}, function(stream) {
var video1 = document.querySelector("#video1")
video1.src = window.URL.createObjectURL(stream)
video1.play()
}, function() {
})
var pc = new RTCPeerConnection()
pc.createOffer(function success(offer) {
var sdp = offer;
alert(JSON.stringify(sdp))
}, function error() {
})
var btn = document.querySelector("#btn");
btn.addEventListener('click', function() {
console.log("clicked")
var lesdp = JSON.parse(document.querySelector('#lesdp').value);
pc.setRemoteDescription(new RTCSessionDescription(lesdp), function(streamremote) {
var video2 = document.querySelector("#video2");
video2.srcObject = window.URL.createObjectURL(streamremote)
video2.play()
}, function() {
})
})
</script>
</html>
You can test it here: https://matr.fr/webrtc.html
Open a navigator, copy the popup offer string object, paste it into the textarea, then click "Activer" and look at the error in the console.
So when I click on the "Activer" button, it has this error:
Failed to execute 'createObjectURL' on 'URL': No function was found
that matched the signature provided.
Please help me. I use Google Chrome to test it.
You're calling window.URL.createObjectURL(undefined) which produces that error in Chrome.
streamremote is undefined because setRemoteDescription resolves with nothing by design.
You've only got about half the code needed to do a cut'n'paste WebRTC demo. Compare here.

Using WebRTC getStat() API

Hey I am trying to implement the getstat API in my WebRTC application. Im finding it hard to get any tutorials at all , at a beginners level.
My Application
I created a 2 person chat-room using the peer js framework. so in my application I am using what can be described a "Sneeker-net" for signaling , ie I am manually sharing a peer id with the person I want a chat with via giving them my id in a email lets say then they call that ID . it uses the stun and turn servers to make our connections its a simple peer to peer chat with Html5 and JavaScript which uses the peerjs API.
here is my HTML 5 AND Javascript code
HTML5 code
<html>
<head>
<title> PeerJS video chat with manual signalling example</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.peerjs.com/0.3/peer.js"></script>
<script type="text/javascript" src="ps-webrtc-peerjs-start.js ></script>
</head>
<body>
<div>
<!-- Video area -->
<div id="video-container">
Your Friend<video id="their-video" autoplay class="their-video"></video>
<video id="my-video" muted="true" autoplay class="my-video"></video> You
</div>
<!-- Steps -->
<div>
<h2> PeerJS Video Chat with Manual Signalling</h2>
<!--Get local audio/video stream-->
<div id="step1">
<p>Please click 'allow' on the top of the screen so we can access your webcam and microphone for calls</p>
<div id="step1-error">
<p>Failed to access the webcam and microphone. Make sure to run this demo on an http server and click allow when asked for permission by the browser.</p>
Try again
</div>
</div>
<!--Get local audio/video stream-->
<!--Make calls to others-->
<div id="step2">
<p>Your id: <span id="my-id">...</span></p>
<p>Share this id with others so they can call you.</p>
<p><span id="subhead">Make a call</span><br>
<input type="text" placeholder="Call user id..." id="callto-id">
Call
</p>
</div>
<!--Call in progress-->
<!--Call in progress-->
<div id="step3">
<p>Currently in call with <span id="their-id">...</span></p>
<p>End call</p>
</div>
</div>
</div>
</body>
</html>
My Javascript file
navigator.getWebcam = (navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
// PeerJS object ** FOR PRODUCTION, GET YOUR OWN KEY at http://peerjs.com/peerserver **
var peer = new Peer({
key: 'XXXXXXXXXXXXXXXX',
debug: 3,
config: {
'iceServers': [{
url: 'stun:stun.l.google.com:19302'
}, {
url: 'stun:stun1.l.google.com:19302'
}, {
url: 'turn:numb.viagenie.ca',
username: "XXXXXXXXXXXXXXXXXXXXXXXXX",
credential: "XXXXXXXXXXXXXXXXX"
}]
}
});
// On open, set the peer id so when peer is on we display our peer id as text
peer.on('open', function() {
$('#my-id').text(peer.id);
});
peer.on('call', function(call) {
// Answer automatically for demo
call.answer(window.localStream);
step3(call);
});
// Click handlers setup
$(function() {
$('#make-call').click(function() {
//Initiate a call!
var call = peer.call($('#callto-id').val(), window.localStream);
step3(call);
});
$('end-call').click(function() {
window.existingCall.close();
step2();
});
// Retry if getUserMedia fails
$('#step1-retry').click(function() {
$('#step1-error').hide();
step();
});
// Get things started
step1();
});
function step1() {
//Get audio/video stream
navigator.getWebcam({
audio: true,
video: true
}, function(stream) {
// Display the video stream in the video object
$('#my-video').prop('src', URL.createObjectURL(stream));
// Displays error
window.localStream = stream;
step2();
}, function() {
$('#step1-error').show();
});
}
function step2() { //Adjust the UI
$('#step1', '#step3').hide();
$('#step2').show();
}
function step3(call) {
// Hang up on an existing call if present
if (window.existingCall) {
window.existingCall.close();
}
// Wait for stream on the call, then setup peer video
call.on('stream', function(stream) {
$('#their-video').prop('src', URL.createObjectURL(stream));
});
$('#step1', '#step2').hide();
$('#step3').show();
}
Many thanks to anybody who takes time out to help me I am very grateful, as Im only a beginner at WebRTC .
Cheers
Here is my code, which works in both Chrome and Firefox. It traces stats in the browser console. Because Chrome stats are very verbose, I filter them following an arbitrary criteria (statNames.indexOf("transportId") > -1):
function logStats() {
var rtcPeerConn = ...;
try {
// Chrome
rtcPeerConn.getStats(function callback(report) {
var rtcStatsReports = report.result();
for (var i=0; i<rtcStatsReports.length; i++) {
var statNames = rtcStatsReports[i].names();
// filter the ICE stats
if (statNames.indexOf("transportId") > -1) {
var logs = "";
for (var j=0; j<statNames.length; j++) {
var statName = statNames[j];
var statValue = rtcStatsReports[i].stat(statName);
logs = logs + statName + ": " + statValue + ", ";
}
console.log(logs);
}
}
});
} catch (e) {
// Firefox
if (remoteVideoStream) {
var tracks = remoteVideoStream.getTracks();
for (var h=0; h<tracks.length; h++) {
rtcPeerConn.getStats(tracks[h], function callback(report) {
console.log(report);
}, function(error) {});
}
}
}
}
You need the rtcPeerConnection, and Firefox requires the stream in addition.
for twilio SDK look at this post:
Is there an API for the chrome://webrtc-internals/ variables in javascript?
var rtcPeerConn =Twilio.Device.activeConnection();
rtcPeerConn.options.mediaStreamFactory.protocol.pc.getStats(function callback(report) {
var rtcStatsReports = report.result();
for (var i=0; i<rtcStatsReports.length; i++) {
var statNames = rtcStatsReports[i].names();
// filter the ICE stats
if (statNames.indexOf("transportId") > -1) {
var logs = "";
for (var j=0; j<statNames.length; j++) {
var statName = statNames[j];
var statValue = rtcStatsReports[i].stat(statName);
logs = logs + statName + ": " + statValue + ", ";
}
console.log(logs);
}
}
});
I advice you to read Real-Time Communication with WebRTC for O'Reilly
It is very useful book for beginners in addition the book will guide you to build your webchat application ste by step using sokcet.io for signaling
the link in the first comment

Web audio API and multiple inputs mic device

I have an audio device with 4 inputs microphones..
Someone knows if i can use all these inputs with Web audio API ?
Thanks !
It should work by calling getUserMedia four times, choosing a different device each time, and using createMediaStreamSource four times, although I haven't tested.
yes,you can list all input devices and select one to use.
<html><body>
<select id="devices_list"></select>
<script>
function devices_list(){
var handleMediaSourcesList = function(list){
for(i=0;i<list.length;i++){
var device= list[i];
if(device.kind == 'audioinput') {
document.querySelector('#devices_list').options.add(new Option(device.label ,device.deviceId));
}
}
}
if (navigator["mediaDevices"] && navigator["mediaDevices"]["enumerateDevices"])
{
navigator["mediaDevices"]["enumerateDevices"]().then(handleMediaSourcesList);
}
// Old style API
else if (window["MediaStreamTrack"] && window["MediaStreamTrack"]["getSources"])
{
window["MediaStreamTrack"]["getSources"](handleMediaSourcesList);
}
}
function usemic(){
navigator.getUserMedia ({
"audio":{
"optional": [{
"sourceId": document.querySelector('#devices_list').value
}]
}}, function (stream) {
//...some code to use stream from mic
},function(err){
debuginfo('getMedia ERR:'+err.message );
});
}
</script>
</body></html>

I am trying to make an application that tracks multiple users

I am trying to make a application that tracks multiple people on Google maps and allows the user to see who he wants to track.
I would like this app to send the long and lat to mysql. I am having trouble trying to get the longitude and latitude of the user to update in mysql. What is the best way to to do this?
All i want to do is track multiple people and plot them on a user map, so if the user wanted to see where his friends where at it would show on his cell phone.
If you are using web, you can get each users location from the browser using geolocation:
http://www.w3schools.com/html/html5_geolocation.asp
Since you don't say what your app is written in though we cannot offer any more specific advice.
You will then need to upload that to your app and store it in the database along with a key identifying each user.
The client would then have to be able to pick which of these users they wish to view, at which point you would draw them on a map using something like Google Maps API:
https://developers.google.com/maps/
<!DOCTYPE html>
<html>
<!--
geoLocMap.html by Bill Weinman
<http://bw.org/contact/>
created 2011-07-07
updated 2011-07-20
Copyright (c) 2011 The BearHeart Group, LLC
This file may be used for personal educational purposes as needed.
Use for other purposes is granted provided that this notice is
retained and any changes made are clearly indicated as such.
-->
<head>
<title>
Geolocation Map Test (1.1.3)
</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas { height: 100%; width: 100% }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">
var watchID;
var geo; // for the geolocation object
var map; // for the google map object
var mapMarker; // the google map marker object
// position options
var MAXIMUM_AGE = 200; // miliseconds
var TIMEOUT = 300000;
var HIGHACCURACY = true;
function getGeoLocation() {
try {
if( !! navigator.geolocation ) return navigator.geolocation;
else return undefined;
} catch(e) {
return undefined;
}
}
function show_map(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var latlng = new google.maps.LatLng(lat, lon);
if(map) {
map.panTo(latlng);
mapMarker.setPosition(latlng);
} else {
var myOptions = {
zoom: 18,
center: latlng,
// mapTypeID --
// ROADMAP displays the default road map view
// SATELLITE displays Google Earth satellite images
// HYBRID displays a mixture of normal and satellite views
// TERRAIN displays a physical map based on terrain information.
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map.setTilt(0); // turns off the annoying default 45-deg view
mapMarker = new google.maps.Marker({
position: latlng,
title:"You are here."
});
mapMarker.setMap(map);
}
}
function geo_error(error) {
stopWatching();
switch(error.code) {
case error.TIMEOUT:
alert('Geolocation Timeout');
break;
case error.POSITION_UNAVAILABLE:
alert('Geolocation Position unavailable');
break;
case error.PERMISSION_DENIED:
alert('Geolocation Permission denied');
break;
default:
alert('Geolocation returned an unknown error code: ' + error.code);
}
}
function stopWatching() {
if(watchID) geo.clearWatch(watchID);
watchID = null;
}
function startWatching() {
watchID = geo.watchPosition(show_map, geo_error, {
enableHighAccuracy: HIGHACCURACY,
maximumAge: MAXIMUM_AGE,
timeout: TIMEOUT
});
}
window.onload = function() {
if((geo = getGeoLocation())) {
startWatching();
} else {
alert('Geolocation`enter code here` not supported.')
}
}
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
</html>