after a couple of hours of struggling here I am. I have the following code, which apparently should just start my webcam and prompt the stream on the webpage:
<!doctype html>
<html>
<head>
<title>HTML5 Webcam Test</title>
</head>
<body>
<video id="sourcevid" autoplay>Put your fallback message here.</video>
<div id="errorMessage"></div>
<script>
video = document.getElementById('sourcevid');
navigator.getUserMedia = navigator.webkitGetUserMedia || navigator.getUserMedia;
window.URL = window.URL || window.webkitURL;
function gotStream(stream) {
if (window.URL) {
video.src = window.URL.createObjectURL(stream);
} else {
video.src = stream; // Opera.
}
video.onerror = function(e) {
stream.stop();
};
stream.onended = noStream;
}
function noStream(e) {
var msg = 'No camera available.';
if (e.code == 1) {
msg = 'User denied access to use camera.';
}
document.getElementById('errorMessage').textContent = msg;
}
navigator.webkitGetUserMedia({video: true}, gotStream, noStream);
</script>
</body>
</html>
No errors in the console, but no webcam stream either. Just the "User denied access to use camera.".
I tried another example, too long to show, but again apparently as soon as I try to run the page the stream falls into the .onended function:
function gotStream(stream) {
video.src = URL.createObjectURL(stream);
video.onerror = function () {
stream.stop();
};
stream.onended = noStream;
[...]
Where noStream is a simple function that prints something:
function noStream() {
document.getElementById('errorMessage').textContent = 'No camera available.';
}
So basically when I'm running the second example I'm shown the "No camera available" on the webpage.
I'm running on Chrome Version 22.0.1229.94, I saw somewhere that I needed to enable some flags, but I couldn't find them in my chrome://flags; the flags' name were Enable MediaStream and Enable PeerConnection, but in my version I only have the second one, which I enabled.
Any thoughts? Is the API I'm using old by any means? Can somebody point me to some working example?
Thanks
According to http://www.webrtc.org/running-the-demos the getUserMedia API is available on stable version as of Chrome 21 without the need to use any flag.
I think the error happens because you are trying to instantiate the stream without to define the url stream properly. Consider that you need to access the url stream differently in Chrome and Opera.
I would create the structure of your code as something like below:
function gotStream(stream) {
if (window.URL) {
video.src = window.URL.createObjectURL(stream) || stream;
video.play();
} else {
video.src = stream || stream; // Opera.
video.play();
}
video.onerror = function(e) {
stream.stop();
};
stream.onended = noStream;
}
function noStream(e) {
var msg = 'No camera available.';
if (e.code == 1) {
msg = 'User denied access to use camera.';
}
document.getElementById('errorMessage').textContent = msg;
}
var options = {video: true, toString: function(){return 'video';}};
navigator.getUserMedia(options, gotStream, noStream);
EDIT:
You need to replace the source video element with the media stream. Edited the code above.
video = document.getElementById('sourcevid');
I recommend for reading these two articles:
http://www.html5rocks.com/en/tutorials/getusermedia/intro/
http://dev.opera.com/articles/view/playing-with-html5-video-and-getusermedia-support/
Related
We have a laptop with one built-in webcam and 2 external USB webcams. I would like to receive images from all three webcams at the same time. I know that since 2018 this is possible.
I am using the following code to work with one camera, but how to display the image from three cameras at once?
<script>
var video = null;
var canvas = null;
var canvasContext = null;
var webimage = null;
var statusLabel = null;
function initVideo() {
video = document.getElementById("monitor");
statusLabel = document.getElementById("LBLSTATUS");
navigator.webkitGetUserMedia({video:true}, gotStream, noStream);
}
function setStatus(aStatus) {
statusLabel.innerHTML = aStatus;
}
function gotStream(stream) {
video.onerror = function () {
stream.stop();
streamError();
};
video.srcObject = stream;
//video.src = webkitURL.createObjectURL(stream); -> Deprecated
}
function noStream() {
setStatus('No camera available.');
}
function streamError() {
setStatus('Camera error.');
}
</script>
You need to get all 3 cameras deviceIDs. Once you get those, make 3 calls to getUserMedia, each with the respective camera ids.
navigator.mediaDevices.getUserMedia({
video: {
deviceId:{
exact: videoSource
},
},
}).then(function( video ) {
const localVidElem = document.getElementById( 'localVideo1' );
localVidElem.srcObject = video;
})
<video id="localVideo1"></video>
Make sure that you have the correct DeviceID and then assign it a srcObject. For more info about that, please read the official WebRTC docs.
I am currently accessing webcam in javascript, then streams to browsers using getUserMedia, caniuse.com shows that Safari and Internet Explorer 11 and above are not able to access getUserMedia.
I use this to check if there is a webcam,
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
Then I display using this :
if (navigator.getUserMedia){
//document.getElementById("webcam").style.display = "block";
window.addEventListener("DOMContentLoaded", function() {
// Grab elements, create settings, etc.
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
video = document.getElementById("video"),
videoObj = { "video": true },
errBack = function(error) {
console.log("Video capture error: ", error.code);
};
// Put video listeners into place
if(navigator.getUserMedia) { // Standard
navigator.getUserMedia(videoObj, function(stream) {
video.src = stream;
video.play();
}, errBack);
}
else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
navigator.webkitGetUserMedia(videoObj, function(stream){
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
}
else if(navigator.mozGetUserMedia) { // Firefox-prefixed
navigator.mozGetUserMedia(videoObj, function(stream){
video.src = window.URL.createObjectURL(stream);
video.play();
}, errBack);
}
// Trigger photo take
document.getElementById("snap").addEventListener("click", function() {
context.drawImage(video, 0, 0, 640, 480);
canvasToDataURLString = canvas.toDataURL();
var blob = dataURItoBlob(canvasToDataURLString);
base64result = canvasToDataURLString.split(',')[1];
//console.debug(base64result);
document.getElementById("base64result").innerHTML = base64result;
});
}, false);
}
Or there simply is no way of accessing webcam using IE and safari? I understand there are limitations in Chrome as the webpage has to be accessed from a secure origin.
I wonder if I am doing it wrongly...
I want to know if there are any other alternatives to getUserMedia!
Thank you and please be kind, I have already tried googling and nth much came out, I am just seeking for alternatives, if it is really impossible, then ok.
Thank you !
IE: no. fuggedaboudit. (the good news is that even older versions of Windows can now use new Edge, and as far as gUM and MediaRecorder go, it is Chromium.)
Safari, both mobile and mac, yes. gUM works, but MediaRecorder is wakky.
These samples let you test what various browsers do, and you can use the source for guidance on your project.
https://webrtc.github.io/samples/
This is the code I used in the index page. I want to let users record a video using their webcam. When I run the app, all I see is space where the video recorder is supposed to be and the stop button. When I do "inspect source" and hover over the area where the recorder is supposed to be, it gets highlighter, that means its their, I just cant see it. Also there is an error shown in the inspect source code which is shown and the code is shown below that.
<script type="text/javascript">
window.URL = window.URL || window.webkitURL;
navigator.getUserMedia =
navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
var video = document.querySelector('video');
var cameraStream = '';
if (navigator.getUserMedia) {
navigator.getUserMedia(
{audio: true, video: true}
function(stream)
{
cameraStream = Stream;
video.src = window.URL.createObjectURL(stream);
}
function()
{
document.writeln("problem")
}
);
}
else
{
document.writeln("not support");
}
document.querySelector('#stopbt').addEventListener(
'click',
function(e)
{
video.src="";
cameraStream.stop();
});
</script>
You need a , in between the } and { (in between lines 64 and 65)
Sorry not a semicolon
Try refreshing because the screenshot has an error but it is different code than the code in the question. The code in the question should work because the user friendly description of the error is the correct error that would show in what the code is.
I'm trying to use the getUserMedia method to access my webcam and track my face with clmtrackr (https://github.com/auduno/clmtrackr).
Some weeks ago it was working but since Chrome update to v50 I encounter issues, it uses the replacement video instead of calling my webcam.
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
// check for camerasupport
if (navigator.getUserMedia) {
var videoSelector = {video : true};
if (window.navigator.appVersion.match(/Chrome\/(.*?) /)) {
var chromeVersion = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
if (chromeVersion < 20) {
videoSelector = "video";
}
};
navigator.getUserMedia(videoSelector, function( stream ) {
if (video.mozCaptureStream) {
video.mozSrcObject = stream;
} else {
video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
}
video.play();
}, function() {
//it uses this alt video
insertAltVideo(video);
alert("There was some problem trying to fetch video from your webcam, using a fallback video instead.");
});
} else {
insertAltVideo(video);
alert("Your browser does not seem to support getUserMedia, using a fallback video instead.");
}
PS : It works as I want on Firefox
Thanks in advance
navigator.getUserMedia no longer works in Chrome (it returns undefined), use the newer MediaDevices interface:
navigator.mediaDevices.getUserMedia(constraints)
.then(function(stream) {
var videoTracks = stream.getVideoTracks();
console.log('Got stream with constraints:', constraints);
console.log('Using video device: ' + videoTracks[0].label);
stream.onended = function() {
console.log('Stream ended');
};
window.stream = stream; // make variable available to console
video.srcObject = stream;
})
.catch(function(error) {
// ...
}
See more:
https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia
https://developers.google.com/web/updates/2015/07/mediastream-deprecations?hl=en
https://developers.google.com/web/updates/2015/10/media-devices?hl=en
This question already has answers here:
Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia
(16 answers)
Closed 6 years ago.
I'm developing a Chrome Extension that uses the background page to access the user's webcam.
Users are given the option to turn the camera off.
The stream appears to be being turned off. The relevant functions are no longer receiving the stream. However the webcam light (currently being developed and tested on a mac book pro) does not turn off.
Any ideas?
Here's my code for setting up the stream:
if (navigator.webkitGetUserMedia!=null) {
var options = {
video:true,
audio:false
};
navigator.webkitGetUserMedia(options,
function(stream) {
vid.src = window.webkitURL.createObjectURL(stream);
localstream = stream;
vid.play();
console.log("streaming");
},
function(e) {
console.log("background error : " + e);
});
}
And here's my method for turning off the stream:
function vidOff() {
clearInterval(theDrawLoop);
ExtensionData.vidStatus = 'off';
vid.pause();
vid.src = "";
localstream.stop();
DB_save();
console.log("Vid off");
}
Any obvious I'm missing?
localstream.stop() has been depreciated and no longer works. See this question and answer:
Stop/Close webcam which is opened by navigator.getUserMedia
And this link:
https://developers.google.com/web/updates/2015/07/mediastream-deprecations?hl=en#stop-ended-and-active
Essentially you change localstream.stop() to localstream.getTracks()[0].stop();
Here's the source in the question updated:
<html>
<head>
<script>
var console = { log: function(msg) { div.innerHTML += "<p>" + msg + "</p>"; } };
var localstream;
if (navigator.mediaDevices.getUserMedia !== null) {
var options = {
video:true,
audio:false
};
navigator.webkitGetUserMedia(options, function(stream) {
vid.src = window.URL.createObjectURL(stream);
localstream = stream;
vid.play();
console.log("streaming");
}, function(e) {
console.log("background error : " + e.name);
});
}
function vidOff() {
//clearInterval(theDrawLoop);
//ExtensionData.vidStatus = 'off';
vid.pause();
vid.src = "";
localstream.getTracks()[0].stop();
console.log("Vid off");
}
</script>
</head>
<body>
<video id="vid" height="120" width="160" muted="muted" autoplay></video><br>
<button onclick="vidOff()">vidOff!</button><br>
<div id="div"></div>
</body>
</html>
The code above works - as shown by #jib here using the above code:
function vidOff() {
vid.pause();
vid.src = "";
localstream.stop();
}
The problem is to do with it being a persistent background page. I'm swapping over to event pages for the Chrome extension as a work around.