WebRTC error while creating video chat app - javascript

I am getting this error on console while refreshing the page.. Everythng else works fine the Chats and everthing.. just the streaming part is not working
NotSupportedError: MediaStreamError
at module.exports (http://192.168.1.10:9966/index.js:3081:17)
at Object.1.getusermedia (http://192.168.1.10:9966/index.js:4:1)
at o (http://192.168.1.10:9966/index.js:1:265)
at r (http://192.168.1.10:9966/index.js:1:431)
at http://192.168.1.10:9966/index.js:1:460
while creating a video chat app
This is my index.js
var getUserMedia = require('getusermedia')
getUserMedia({video: true, audio: false}, function (err, stream) {
var Peer = require('simple-peer')
var peer = new Peer({
initiator: location.hash === '#init',
trickle: false,
stream: stream
})
peer.on('signal', function (data) {
document.getElementById('yourId').value = JSON.stringify(data)
})
document.getElementById('connect').addEventListener('click', function () {
var otherId = JSON.parse(document.getElementById('otherId').value)
peer.signal(otherId)
})
document.getElementById('send').addEventListener('click', function () {
var yourMessage = document.getElementById('yourMessage').value
peer.send(yourMessage)
})
peer.on('data', function (data) {
document.getElementById('messages').textContent += data + '\n'
})
peer.on('stream', function (stream) {
var video = document.createElement('video')
document.body.appendChild(video)
video.src = window.URL.createObjectURL(stream)
video.play()
})
})
This is my index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CHatting Video</title>
</head>
<body>
<label>Your ID:</label><br/>
<textarea id="yourId"></textarea><br/>
<label>Other ID:</label><br/>
<textarea id="otherId"></textarea>
<button id="connect">connect</button>
<br/>
<label>Enter Message:</label><br/>
<textarea id="yourMessage"></textarea>
<button id="send">send</button>
<pre id="messages"></pre>
<script src="index.js" charset="utf-8"></script>
</body>
</html>
When I send a message to other browser it works fine but for video chat it does not work
Any Idea on how to fix this.????

I got the error..
I was using getUserMedia instead of navigator.getUserMedia
getUserMedia has been deprecated.

Related

Google Auth don't work in mobile popup_closed_by_user error

I created an web application (js) that connects with Google. It works on PC but not on mobile. The error indicated is popup_closed_by_user while I did not close the popup!! I would like some help please, here is an example:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://apis.google.com/js/api:client.js"></script>
<title>Document</title>
</head>
<body>
<h3>warning: there is Script Error bc client id is not entered. this example don't work in stackoverflow code snippet</h3>
<h1>name: <span id="namegoogle">not connected</span></h1>
<h1>image: <img id="img_google" alt="not connected"/></h1>
<button id="customBtn">GOOGLE: click to connect</button>
<p>ERROR: <span id="errorgoogle">[NO ERROR]</span></p><br><br><h3>WARNING: CLIENT ID IS NOT DECLARED</h3>
</body>
<script>var is_google_user_succed_942894 = false;
var google_getGivenName = "";var google_getFamilyName = "";var google_getAvatarUrl = "";
var googleUser = {};var startApp = function() {
gapi.load('auth2', function(){
// Retrieve the singleton for the GoogleAuth library and set up the client.
auth2 = gapi.auth2.init({
client_id: '################################################################################################.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
// Request scopes in addition to 'profile' and 'email'
//scope: 'additional_scope'
});
attachSignin(document.getElementById('customBtn'));
});
};
startApp();
function attachSignin(element) {
console.log(element.id);
auth2.attachClickHandler(element, {},
function(googleUser) {
document.getElementById("namegoogle").innerHTML = googleUser.getBasicProfile().getName();
document.getElementById("img_google").src = googleUser.getBasicProfile().getImageUrl();
}, function(error) {
var error_msg = error['error']; document.getElementById('errorgoogle').innerHTML = error_msg;
});
}
</script><script src="https://apis.google.com/js/platform.js?onload=renderButton" async defer></script>
</html>

Streaming Audio from User microphone to multiple users on the browser

Right now I am using Node.js to Javascript to take the microphone audio data from 1 user and to have other people listen to that user's mic audio via browser. I am trying to do this right now with socket.io. How can I achieve this? right now I can send messages but not audio or a simple audio file. It would be awesome if I can livestream the user's microphone audio. Any simple client/server code example would be so appreciated. I've been reading about this for hours and everything seems so confusing. If the problem is too hard, I also have a wav file, but how can I send that? Please help please!
Here is my current code.
Server.js
var http = require("http");
var io = require('socket.io');
var server = http.createServer(function (request, response) {
response.writeHead(200, {
"Content-Type": "text/html"
});
response.write("WebSocket Start~~~~~~~~~~~~");
response.end("");
}).listen(8080);
var socket = io.listen(server);
socket.on('connection', function (client) {
client.on('client-stream-request', function (data) {
var stream = ss.createStream();
var filename = __dirname + '/downloads/' + < YOURSONG.MP3 > ;
ss(socket).emit('audio-stream', stream, {
name: filename
});
fs.createReadStream(filename).pipe(stream);
});
client.on('message', function (event) {
console.log('Received message from client!', event);
client.receive audio from user 1 browser mic ? ? ? ? ? ? ? ?
client.emit('emitMessage', {
hello: 'messgge received, wish you happy' + new
Date().toString()
});
});
client.on('disconnect', function () {
// clearInterval(interval);
console.log('Server has disconnected');
});
client.send('hello, I am the server');
client.send user 1 browser mic audio to everyone connected to the server ? ? ? ? ? ?
});
Here is my client code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
div {
border-radius: 10px;
border: 2px solid pink;
width: 800px;
}
</style>
</head>
<body>
<h1></h1>
<div id="result"></div>
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script>
//创建Socket.IO实例,建立连接
var socket = io.connect('http://localhost:8080');
var audio = document.getElementById('player');
ss(socket).on('audio-stream', function (stream, data) {
parts = [];
stream.on('data', function (chunk) {
parts.push(chunk);
});
stream.on('end', function () {
audio.src = (window.URL || window.webkitURL).createObjectURL(new Blob(parts));
audio.play();
});
});
// 添加一个连接监听器
socket.on('connect', function () {
console.log('Client has connected to the server!');
});
// 添加一个连接监听器
socket.on('message', function (data) {
document.getElementById("result").innerHTML += data + "<br />";
});
socket.on('emitMessage', function (data) {
document.getElementById("result").innerHTML += data.hello + "<br />";
});
// 添加一个关闭连接的监听器
socket.on('disconnect', function () {
console.log('The client has disconnected!');
});
// 通过Socket发送一条消息到服务器
function sendMessageToServer(message) {
socket.send(message);
}
var date = new Date();
var ms = "Time: " + date.toString() + "Today is a nice day, wish you happy";
setInterval("sendMessageToServer(ms)", 1000);
</script>
</body>
</html>

How to receive continuous chunk of video as a blob array and set to video tag dynamically in Websocket

I am trying to make my own broadcasting architecture. In this system i am using Websocket to transfer data since i know it is suitable for continuous data transfer.
In my system there is a Host who initiate webcam live broadcast video. I use MediaStreamRecorder.js which record every 5s chunk of video and send to server through websocket as blob array.
Server simply recieve and send to the all client who are connected in that Session.
When client connected then it receive continuous 5s chunk of video as blob array through Websocket.
My main problem is in Client side how can I set the video blob array to html video source dynamically in every 5 seconds such that it can play every 5s chunk of video data.
I am using Glassfish 4.0 as server and Javscript in Host and Client side. Browser: Chrome
Source Code:
ServerBroadCast.java
package websocket1;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint(value = "/liveStreamMulticast")
public class LiveStreamMultiCast {
private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());
#OnOpen
public void whenOpening(Session session) {
// session.setMaxBinaryMessageBufferSize(1024*512); // 512 KB
sessions.add(session);
System.out.println("You are Connected!");
System.out.println("Total Connection are connected: " + sessions.size());
}
#OnMessage
public void handleVideo(byte[] videoData, Session HostSession) {
// System.out.println("Insite process video");
try {
if (videoData != null) {
sendVideo(videoData, HostSession);
}
} catch (Throwable e) {
System.out.println("Error sending message " + e.getMessage());
}
}
#OnClose
public void onClosing(Session session) {
System.out.println("Goodbye!");
sessions.remove(session);
}
private void sendVideo(byte[] videoData, Session hostSession) throws IOException {
Iterator<Session> iterator = sessions.iterator();
Session tempSession = null;
while (iterator.hasNext()) {
tempSession = iterator.next();
// System.out.println("Sever send data to "+ tempSession);
if (!tempSession.equals(hostSession))
tempSession.getBasicRemote().sendBinary(ByteBuffer.wrap(videoData));
}
}
}
host.html
<html>
<head>
<title>Demo</title>
<script type="text/javascript" src="js/required/mediastream.js"></script>
</head>
<body>
<video id="video" autoplay=""></video>
<button id="stopButton" onclick="stop()">Stop</button>
<script type="text/javascript">
var url = "ws://localhost:8080/LiveTraining3Demo/liveStreamMulticast"; // 8080/application_name/value_given_in_annotation
var socket = new WebSocket(url);
var video = document.querySelector('video');
socket.onopen = function(){
console.log("Connected to Server!!");
}
socket.onmessage = function(msg){
console.log("Message come from server");
}
/////////////////////////////////
var wholeVideo =[];
var chunks = [];
var mediaRecorder;
//////////////////////////////////////
function gotMedia(stream) {
video.srcObject = stream;
mediaRecorder = new MediaStreamRecorder(stream);
console.log("mediaRecorderCalled");
mediaRecorder.mimeType = 'video/webm';
mediaRecorder.start(5000);//
console.log("recorder started");
mediaRecorder.ondataavailable = (event) =>{
chunks.push(event.data);
console.log("push B");
wholeVideo.push(event.data);
console.log("WholeVideo Size:");
setTimeout(sendData(),5010);
}
}
function sendData(){
//var byteArray = new Uint8Array(recordedTemp);
const superBuffer = new Blob(chunks, {
type: 'video/webm'
});
socket.send(superBuffer);
console.log("Send Data");
console.table(superBuffer);
chunks = [];
}
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
navigator.mediaDevices.getUserMedia({video: true , audio: true})
.then(gotMedia)
.catch(e => { console.error('getUserMedia() failed: ' + e); });
</script>
</body>
</html>
client.html
<html>
<head>
<title>Recieve Video</title>
</head>
<body>
<video id="video" autoplay controls loop
style="width: 700; height: 500; margin: auto">
<source src="" type="video/webm">
</video>
<script>
var url = "ws://localhost:8080/LiveTraining3Demo/liveStreamMulticast"; // 8080/application_name/value_given_in_annotation
var check = true;
var socket = new WebSocket(url);
var videoData = [];
var superBuffer = null;
//var videoUrl;
//socket.binaryType = 'arraybuffer';
socket.onopen = function() {
console.log("Connected!!");
}
var check = true;
socket.onmessage = function(videoStream) {
var video = document.querySelector('video');
var videoUrl = window.URL.createObjectURL(videoStream.data);
video.src = videoUrl;
video.load();
video.onloadeddata = function() {
URL.revokeObjectURL(video.src);
video.play();
}
//video.srcObject
//video.play();
console.table(videoStream);
}
socket.onerror = function(err) {
console.log("Error: " + err);
}
</script>
</body>
</html>
When I try to run all other looks fine but in client.html only the video tag source is display with no any video play.
I am working on it since a week.
Might be my some implementation goes wrong, I also know WebRTC, Mauz Webrtc Broadcast but i didn't like to go through that complex if there is another simple way to do that. I am not like to use node.js server since i have to make this web application with spring.
Any idea can be appreciated.
Thanks In Advance!!.
In client side will get array buffer. So you need to convert array buffer into blob array.
let video = document.querySelector('video');
let blobArray = [];
socket.on('message',data=>{
blobArray.push(new Blob([new Uint8Array(data)],{'type':'video/mp4'}));
let currentTime = video.currentTime;
let blob = new Blob(blobArray,{'type':'video/mp4'});
video.src = window.URL.createObjectURL(blob);
video.currentTime = currentTime;
video.play();
});

html5 getUserMedia Api stop webcam button not working

I am executing this code on localhost XAMPP Server
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<video onclick="changeFilter(this);"width=200 height=200 id="video" controls autoplay></video>
<p>
<button onclick="startWebcam();">Start WebCam</button>
<button onclick="stopWebcam();">Stop WebCam</button>
</p>
<script>
navigator.getUserMedia = ( navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
var webcamStream;
function startWebcam() {
if (navigator.getUserMedia) {
console.log("toto");
navigator.getUserMedia (
// constraints
{
video: true,
audio: false
},
// successCallback
function(localMediaStream) {
var video = document.querySelector('video');
video.src = window.URL.createObjectURL(localMediaStream);
webcamStream = localMediaStream;
},
// errorCallback
function(err) {
console.log("The following error occured: " + err);
}
);
} else {
console.log("getUserMedia not supported");
}
}
function stopWebcam() {
localMediaStream.stop();
}
</script>
</body>
</html>
This code starts my webcam, but when I press the Stop WebCam button the console gives me the following error:
Uncaught TypeError: Cannot read property 'stop' of undefined function stopWebcam() { webcamStream.stop(); }
I am a JavaScript newbie and I can not see the issue here.
localMediaStream is not available to you in stopWebcam(). Check out this post for more on What is the scope of variables in JavaScript?
Try...
function stopWebcam() {
webcamStream.stop();
}

Failed to load resource - Socket.IO

I have been trying my hand at node.js and socket.io, and following a tutorial. I keep getting an error from an application i am building. This is my server.js file:
var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var cache = {};
var chatServer = require('./lib/chat_server.js');
chatServer.listen(server);
//file doesn't exist
function send404(response) {
response.writeHead(404, {'Content-Type': 'text/plain'});
response.write('Error 404: resource not found.');
response.end();
}
//handles serving file data
function sendFile(response, filePath, fileContents) {
response.writeHead(
200,
{"content-type": mime.lookup(path.basename(filePath))}
);
response.end(fileContents);
}
//cache static files to memory
function serveStatic(response, cache, absPath) {
if (cache[absPath]) {
sendFile(response, absPath, cache[absPath]);
} else {
fs.exists(absPath, function(exists) {
if (exists) {
fs.readFile(absPath, function(err, data) {
if (err) {
send404(response);
}
else {
cache[absPath] = data;
sendFile(response, absPath, data);
}
});
}
else {
send404(response);
}
});
}
}
var server = http.createServer(function(request, response) {
var filePath = false;
if (request.url == '/') {
filePath = 'public/index.html';
}
else {
filePath = 'public' + request.url;
}
var absPath = './' + filePath;
serveStatic(response, cache, absPath);
});
server.listen(3001, function() {
console.log("Server listening on port 3001.");
});
This is my index.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Chat</title>
<meta name="description" content="An interactive chat application using websockets.">
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<div id='content'>
<div id='room'></div>
<div id='room-list'></div>
<div id='messages'></div>
<form id='send-form'>
<input id='send-message' />
<input id='send-button' type='submit' value='Send'/>
<div id='help'>
Chat commands:
<ul>
<li>Change nickname: <code>/nick [username]</code></li>
<li>Join/create room: <code>/join [room name]</code></li>
</ul>
</div>
</form>
</div>
<script src="[localserver here]:3001/socket.io/socket.io.js" type="text/javascript"></script>
<script src="/javascripts/jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="/javascripts/chat.js" type="text/javascript"></script>
<script src="/javascripts/chat_ui.js" type="text/javascript"></script>
</body>
</html>
Upon loading "[localserver here]:3001" from the browser, the index page appears with the ensuing CSS. But when i try an event, like sending a message, i get this error:
Error 404: resource not found.
I right-clicked and inspected element from my Chrome browser and got this two messages:
Failed to load resource: the server responded with a status of 404 (Not Found) "[localserver here]:3001/socket.io/socket.io.js"
Uncaught ReferenceError: io is not defined "[localserver here]:3001/javascripts/chat_ui.js:26"
This is line 26 from my chat_ui.js file:
var socket = io.connect('[localserver here]:3001');
$(document).ready(function() {
var chatApp = new Chat(socket);
socket.on('nameResult', function(result) {
var message;
if (result.success) {
message = 'You are now known as ' + result.name + '.';
} else {
message = result.message;
}
$('#messages').append(divSystemContentElement(message));
});
socket.on('joinResult', function(result) {
$('#room').text(result.room);
$('#messages').append(divSystemContentElement('Room changed.'));
});
socket.on('message', function (message) {
var newElement = $('<div></div>').text(message.text);
$('#messages').append(newElement);
});
socket.on('rooms', function(rooms) {
$('#room-list').empty();
for(var room in rooms) {
room = room.substring(1, room.length);
if (room != '') {
$('#room-list').append(divEscapedContentElement(room));
}
}
$('#room-list div').click(function() {
chatApp.processCommand('/join ' + $(this).text());
$('#send-message').focus();
});
});
setInterval(function() {
socket.emit('rooms');
}, 1000);
$('#send-message').focus();
$('#send-form').submit(function() {
processUserInput(chatApp, socket);
return false;
});
})
I have tried all sorts. Initially line 26 was var socket = io.connect(); and i changed it to the one above. I also changed the directory of socket.io.js in the index.html file from:
to
...as i thought this was the problem, but it is still giving me the same error.
Please how do i resolve this?
(PS - I am using Brackets as my IDE for node.js development. Also, i used "[localserver]" to indicate the localhost)
Try this:
<script type="text/javascript" src='http://localhost:3001/socket.io/socket.io.js'>
</script>
<script type="text/javascript">
var socket = io.connect('http://localhost:3001');
socket.on('connect',function(){
console.log("connect");
});
</script>
It must help you.
The line chatServer.listen(server); should be after you run your server.
chartServer is listening to the server but that one is not running yet.
Try to move this line:
chatServer.listen(server);
to the end of your script server.js

Categories

Resources