Turn off webcam/camera after using getUserMedia [duplicate] - javascript

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.

Related

How to fix this error : NotReadableError: Could not start video source

I am trying to implement video recording but getting this error. i have 2 buttons called Front Camera ,Back Camera. On click i am calling below method. first it displays the camera correctly but while switching camera it gives me the error. Please help how to fix the problem ?
function StartVideoCamera(obj) {
var id = $(obj).attr('id');
var camNode = $(obj).attr('cammode');
if (camNode != 'user') {
camNode = eval('{ exact: "environment" }')
}
var video = document.querySelector('#video' + id);
var constraints = { audio: true, video: { width: videoHeight, height: videoWidth, facingMode: camNode
} };
navigator.mediaDevices.getUserMedia(constraints)
.then(function (mediaStream) {
window.stream = null;
video.srcObject = null;
recordButton.disabled = false;
window.stream = mediaStream;
video.srcObject = mediaStream;
video.onloadedmetadata = function (e) {
video.play();
};
})
.catch(function (err) {
alert(err.name + ": " + err.message)
console.log(err.name + ": " + err.message);
});
}
You need to stop the previous mediaStreamObj before calling getUserMedia again.
This happens when your other(front/back) is already in use. You need to release the camera first.
stream.getTracks()
.forEach(track => track.stop());
Here stream is what you got from getUserMedia
This stops all the devices (you can check that the camera light goes off on the desktop) and (on mobile devices).

Multiple webcams per browser page

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.

webrtc remote video on firefox not work

iam use webrtc for made an video call when i made an call between chrome and chrome work without problem
but when i made call with firefox ... firefox share video to chrome but video from chrome not shown in firefox i think there are problem in attach mediastream for firefox because
the video element src read this
<video id="remoteVideo" autoplay="" src="[object MediaStream]"></video>
and in console of firefox its show this
404 failed to load http://localhost/videocall/[object%20MediaStream].
and this is my code for attach stream to video element
pc.onaddstream = function(event) {
var ts = document.getElementById("remoteVideo");
attachMediaStreamx(ts, event.stream);
};
attachMediaStreamx = function(element, stream) {
if (typeof element.srcObject !== 'undefined') {
element.srcObject = stream;
} else if (typeof element.mozSrcObject !== 'undefined') {
element.mozSrcObject = stream;
} else if (typeof element.src !== 'undefined') {
element.src = URL.createObjectURL(stream);
} else {
console.log('Error attaching stream to element.');
}
};
Just try
pc.onaddstream = function(event) {
remoteVideo.srcObject = event.stream;
};
You should not have src="[object MediaStream]" in your HTML code. Just remove that bit. It is probably interfering with the srcObject.

MediaRecorder videos longer than a few seconds don't play back

I'd like to record a video in the browser and then play it back for the user. I'm currently using the MediaRecorder API (only available in Firefox for now) to do this. It works fine for videos shorter than a few seconds, but otherwise the video doesn't show up at all.
There are no errors in the console or similar, and I couldn't find anything about any file size limitations in the documentation.
Here's the code I'm using (Firefox only):
index.html:
<!DOCTYPE html>
<html>
<body>
<button id="start">Start</button>
<button id="stop">Stop</button>
<video id="player" src="" width="300" height="300" autoplay></video>
<script src="script.js"></script>
</body>
</html>
script.js:
var record = document.getElementById('start');
var stop = document.getElementById('stop');
var video = document.getElementById('player');
var constraints = {video: true};
var onSuccess = function(stream) {
var mediaRecorder = new MediaRecorder(stream);
record.onclick = function() {
mediaRecorder.start();
}
stop.onclick = function() {
mediaRecorder.stop();
}
mediaRecorder.ondataavailable = function(e) {
video.src = window.URL.createObjectURL(e.data);
}
};
var onError = function(err) {
console.log('The following error occured: ' + err);
}
navigator.mozGetUserMedia(constraints, onSuccess, onError);
On Codepen: http://codepen.io/anon/pen/xGqKgE
Is this a bug/browser issue? Are there any limitations to this API that I'm not aware of?

"hello world" on webcam capturing in HTML5 fails to work

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/

Categories