DEV Community

Cover image for How to record your web camera only with JavaScript
EneasLari
EneasLari

Posted on • Updated on

How to record your web camera only with JavaScript

Today we will create a web camera recorder with javascript

Basic html page

Create a javascript file index.js and add a reference to the html at line 15:

<script src="index.js"></script>
Enter fullscreen mode Exit fullscreen mode

Next we will create a video element inside a bootstrap container:

<div class="container">
        <video autoplay playsinline webkit-playsinline muted id="videoelement"
            style="max-width: 100%;height: auto;"></video>
 </div>
Enter fullscreen mode Exit fullscreen mode

Now that we have a bootstrap html template lets add javascript that does the job:

Code explanation

  • At line 9 we prompt the user for permission to use camera and microphone

  • If the user accepts then at line 10 the gotStream function is executed.

  • gotStream add as source of video the stream of camera and microphone

  • If the user denies the permission or stream is inaccessible then at line 11 we prompt the user to reload the page in order to try again

Lets add two buttons one for starting recording and one for stoping it line 17 and 18(this is also the final html page):

Media recorder
Lets get back to our javascript file to do the magic

  • First we must add a MediaRecorder object and initialize it when we get the stream at line 26

  • At line 33 an event listener is added to the rec button. On click the recording starts

  • At line 41 the recording stops when the stop button is clicked.

  • After the recording has stopped the handleDataAvailable is executed and the download function downloads the recorded chunks as webm file.

Source Code

Thanks for your time.
Leave a question or comment below.

Top comments (0)