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>
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>
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 microphoneIf 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 26At 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 thedownload
function downloads the recorded chunks as webm file.
Thanks for your time.
Leave a question or comment below.
Top comments (0)