Let's see some more examples of what we can do with the getUserMedia API: start/stop the webcam, take a screenshot from the current video stream from the webcam, and apply CSS effects in real time. Below, we give links to some cool examples available on the Web.
In order to stop the webcam and make the hardware "unlock it", you need to call the stop() method of the video stream.
Code source:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>webcam start/stop</title>
<script>
let webcamStream;
function startWebcam() {
// request video and audio stream from the user's webcam
navigator.mediaDevices.getUserMedia({
audio: true,
video: true
}).then((stream) => {
let video = document.querySelector('#video');
video.srcObject = stream;
video.play();
webcamStream = stream;
}).catch((error) => {
console.log('navigator.getUserMedia error: ', error);
});
}
function stopWebcam() {
webcamStream.getTracks()[0].stop(); // audio
webcamStream.getTracks()[1].stop(); // video
}
</script>
</head>
<body >
<video width=400 height=400 id="video" controls></video>
<p>
<button onclick="startWebcam();">Start webCam</button>
<button onclick="stopWebcam();">Stop webCam</button>
</p>
</body>
</html>
Lines 11-13: we call navigator.getUserMedia. The parameters indicate that we want to capture the video and the audio from the current device (default webcam). The call to getUserMedia returns an ES6 promise, consisting of the then(stream) method that follows.
Line 14: the then(stream) method is called in case of success and gets the current audio/video stream as parameter. This is passed by the browser to your JavaScript code.
Lines 15-19: The line 16 sets the audio/video stream of the default webcam to the srcObject attribute of the video element, while line 17 starts displaying it in the video player (there can be more than one webcam, we'll see how to select one in particular next). Line 19 stores the stream in a global variable so that we can use it from another function (for stopping/starting the webcam...)
Lines 20-22 define the catch method called in case of error (it could be that the webcam cannot be accessed, or authorizations have not been granted).
Lines 25-27: a function for stopping the webcam. We use the global variable webcamStream here, which was initialized when we started using the webcam in line 19. We have to stop the audio and the video streams separately.
Try this example that shows how to use the getUserMedia API. Note the CSS effects (click on the video to cycle from one effect to another):
The trick is to copy and paste the current image from the video stream into a <canvas> element.
We will look at this example in greater detail in the next course section (related to the <canvas> element).
Webcam Toy: video effects on Paul Neave's webcam (using WebGL)