Skip to content

Instantly share code, notes, and snippets.

@s-shin
Created November 4, 2012 10:05
Show Gist options
  • Save s-shin/4011149 to your computer and use it in GitHub Desktop.
Save s-shin/4011149 to your computer and use it in GitHub Desktop.
Snipet to setup user media by WebRTC
// ## Snipet to setup user media by WebRTC (modified at 20121104)
// This code checked on GC(22), Opera(12), Fx(Nightly) in Mac OSX.
// In addition, only the FaceTime camera is tested.
// Compatibility table: http://caniuse.com/stream
var setupUserMedia = function(media, fn) {
if (arguments.length == 1) {
fn = media;
media = {video: true, audio: true};
}
var getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia || navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
if (!getUserMedia)
return fn("WebRTC is not supported.");
// for legacy
media.toString = function() {
var t = [];
for (var type in media)
t.push(type);
return t.join(",");
};
// call getUserMedia
getUserMedia.call(navigator, media, function(stream) {
var video = document.createElement("video");
if (navigator.mozGetUserMedia) {
// CAUTION: Many fakes exist ;-(
// https://developer.mozilla.org/en-US/docs/WebRTC/taking_webcam_photos
video.mozSrcObject = stream;
} else {
var URL = window.URL || window.webkitURL; // need prefix on Webkit
video.src = URL.createObjectURL(stream);
}
// wait a moment because the video size cannot be got immediately (why?)
video.play(); // need play in order to do that
setTimeout(function wait() {
if (video.videoWidth > 0)
return fn(null, video); // OK, go next
setTimeout(wait, 20);
}, 4);
}, function(err) {
fn(err);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment