WebRTC

WebRTC stands for Web Real Time Communication. We'll get more into this next week but I want to get started with one portion:

getUserMedia

getUserMedia is a method specified as part of WebRTC that allows access to the microphone and webcam of users.

// These help with cross-browser functionality (shim)
window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

// The video element on the page to display the webcam
var video = document.getElementById('thevideo');

// if we have the method
if (navigator.getUserMedia) {
	navigator.getUserMedia({video: true}, function(stream) {
			video.src = window.URL.createObjectURL(stream) || stream;
			video.play();
		}, function(error) {alert("Failure " + error.code);});
}		
		

ALERT!! getUserMedia requires HTTPS ALERT!!

One cool aspect of this is that you can draw the video on to a canvas as well (perhaps to manipulate it):

// Canvas element on the page
var thecanvas = document.getElementById('thecanvas');
var thecontext = thecanvas.getContext('2d');

var draw = function() {
	// Draw the video onto the canvas
	thecontext.drawImage(video,0,0,video.width,video.height);
	
	
	document.getElementById('imagefile').src = dataUrl;
	
	// Draw again in 3 seconds
	setTimeout(draw,3000);	
};

draw();			
		

From the canvas, you can create an image and send that via Socket.io to everyone else, making a poor persons video server:

// Create a data URL from the canvas
var dataUrl = thecanvas.toDataURL('image/webp', 1);

// Optionally draw it to an image object to make sure it works
document.getElementById('imagefile').src = dataUrl;

// Send it via our socket server the same way as we send the image
socket.emit('image', dataUrl);
		
		

Here is a full example

More Information: Capturing Audio and Video in HTML5