Hi,
i’m trying to implemente a html code to detect stream of my webcam that can be played or stopped.
This code doesn’t work ! Why?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta content="Display Webcam Stream" name="title">
<title>Display Webcam Stream</title>
<style>
body {
margin: 30px;
}
h1 {
font-family: sans-serif;
color: #666;
}
#container {
width: 500px;
height: 375px;
border: 10px #333 solid;
}
#videoElement {
width: 500px;
height: 375px;
background-color: #666;
}
button {
margin-top: 20px;
font-size: 12px;
font-weight: bold;
padding: 5px;
background-color: white;
border: 5px solid black;
}
button:hover {
background-color: yellow;
}
button:active {
background-color: yellowgreen;
}
</style>
</head>
<body>
<h1>Stop Webcam Stream</h1>
<div id="container">
<video autoplay="true" id="videoElement"></video>
</div>
<button id="play">Play Video</button>
<button id="stop">Stop Video</button>
<script>
<!--var video = document.querySelector("#videoElement");-->
var playVideo = document.querySelector("#play");
var stopVideo = document.querySelector("#stop");
var video = document.getElementById('videoElement');
playVideo.addEventListener("click", play, true);
stopVideo.addEventListener("click", stop, false);
if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true })
.then(function (stream) {
video.srcObject = stream;
})
.catch(function (error) {
console.log("Something went wrong!", error);
});
}
function play() {
var stream = video.srcObject;
if (stream == null) {
navigator.mediaDevices.getUserMedia({ video: true })
.then(function (stream) {
video.srcObject = stream;
stopVideo.disabled = false;
})
.catch(function (error) {
console.log("Something went wrong!", error);
});
}
}
function stop() {
var stream = video.srcObject;
if (stream) {
var tracks = stream.getTracks();
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
track.stop();
}
video.srcObject = null;
stopVideo.disabled = true;
}
}
// Check if the video stream is present
function checkStream() {
if (video.error) {
console.log('Stream absent');
} else {
console.log('Stream present');
}
}
// Call checkStream() every second
setInterval(checkStream, 1000);
</script>
</body>
</html>
thank for your help