Vote count: 0
I want to create a web application that takes a stream from web camera, sends the stream to a server created with node.js which then broadcasts to all the other users.
My HTML code with Javascript is given below:
<html>
<head>
<title>Webcam streaming</title>
<script src = "/http://ift.tt/1aeIZU4"></script>
</head>
<body>
<button onClick="startStreaming()">Choose to stream</button>
<script>
var video = document.createElement('video');
video.autoplay = true;
video.style.width = 500;
video.style.height = 500;
var socket = io();
socket.on('stream', function(stream){
document.body.appendChild(video);
video.src = URL.createObjectURL(stream);
video.load();
})
function startStreaming() {
document.body.appendChild(video);
var constraints = {video:true, audio:true}
navigator.mediaDevices.getUserMedia(constraints)
.then(function(stream){
video.src = URL.createObjectURL(stream);
video.load();
socket.emit("stream", stream);
})
}
</script>
</body>
</html>
Code at the server side is :
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
app.get('/', function(req, res){
res.sendFile(__dirname + "/html/index.html")
})
server.listen(3000, function () {
console.log("listening to port 3000");
});
io.on('connection', function (socket){
console.log("a user connected");
socket.on('stream', function(stream){
console.log("we are streaming");
io.sockets.emit('stream', stream);
})
socket.on('disconnect', function () {
console.log("a user disconnected");
})
})
As you can see from the code above, I used getUserMedia, took the stream and projected it onto the video element. Then, I used socket.emit to send the data to the server side code, which on receiving the stream, then redirects to all the other users connected. After receiving the stream, I loaded it onto the newly created video element (of course on a different tab). But, the video does not load. What did I do wrong here? Should I use different npm module for video streams like these? I read every questions asked here on stackoverflow but could not find a solution.
Broadcast your webcam using node.js and socket.io
Aucun commentaire:
Enregistrer un commentaire