Ever wondered how you can stream your own webcam recording live on HTML page?
Well, in this quick and easy post, we will have a look at how you can live stream your webcam straight to your HTML page.
Let's get started.
HTML required for this short demo is one liner. Create a file index.html and paste the following:
1<video id="myVidPlayer" controls muted autoplay></video>
This embeds a Simple HTML5 video player to your page.
controls muted autoplay are optional parameters to video tag, which clearly describe their purposes.
Now, it's time to add some life to the video player. This code will Stream your Webcam recording to the created video player.
getUserMedia() is a function which needs an object as a parameter with either of audio/video as a compulsory property set to true. Else, you will get an error. This function then returns a Promise.
Upon running this code, browser will ask for our permission for the usage of Microphone and Camera. If you "allow" it to use, then our
Promise resolves with "stream" as a parameter which we assign it to
video.srcObject. This sets the stage up for playing the video. Upon successful loading of metadata of our video player (video.onloadmetadata), we start the actual streaming with
video.play() and you will see your "beautiful" face right there on your HTML page, else it is rejected with an alert box popup
Bonus : Snapshot of current video frame
Now, we will add a button which will get the snapshot of the current video frame on click and will display it to you in a canvas element.
1<button onclick="snapshot()">Snapshot</button>23<div class="mycanvas">4 <h6>Captured snapshot</h6>5 <canvas></canvas>6</div>
On clicking the button, canvas context is filled with a 2D rectangle with
h=height. (0,0) is passed to tell that we want to fill the context from left top corner of the canvas. Then, we attach our video frame snapshot to the canvas and make it visible with
display:"block" which was hidden by default. More info on Canvas API is here.
Here is the Code pen link Codepen.
This was it for this short and sweet tutorial. See you next time ;)