I have this piece of code, that activates my webcam:
var video = document.getElementById('video');
// Get access to the camera!
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
// Not adding `{ audio: true }` since we only want video now
navigator.mediaDevices.getUserMedia({ video: true }).then(function (stream) {
video.srcObject = stream;
video.play();
});
}
When running the code above, the browser asks for permission to use the webcam. Let's assume that I allow it. The webcam is active now.
What I want now, is to write some code that checks if the webcam is active/being used. So I want to do something like this:
if(navigator.mediaDevices.getUserMedia == true) {
alert("The camera is active");
}
I found a similar post which has a solution, but I guess I am doing something wrong, even though I tried to follow the same solution. The post is here: How to check with JavaScript that webcam is being used in Chrome
Here is what I tried:
function isCamAlreadyActive() {
if (navigator.getUserMedia) {
navigator.getUserMedia({
video: true
}), function (stream) {
// returns true if any tracks have active state of true
var result = stream.getVideoTracks().some(function (track) {
return track.enabled && track.readyState === 'live';
});
}
if (result) {
alert("Already active");
return true;
}
}
alert("Not active");
return false;
}
My solution always returns false, even when the webcam is active