Welcome folks today in this blog post we will be building a screen recorder
in browser using mediarecorder
library and download it as mp4 video
file in browser. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an index.html
file and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Javascript MediaRecorder Project to Record Screen</title> </head> <body> <!-- HTML for start and stop buttons --> <button id="start-button" onclick="start()">Start Recording</button> </body> </html> |
As you can see we have the start
button where we have binded onclick
event listener where we are executing the start()
method where we allow the user to record the screen
for some time and download it as mp4 video
file
Now we need to write the javascript
code to make the start()
method as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
function start(){ // Request permission to capture the screen navigator.mediaDevices.getDisplayMedia({video: true}).then(stream => { // Create a new MediaRecorder const recorder = new MediaRecorder(stream); // Start recording recorder.start(); // Create an empty buffer to hold the recorded data const buffer = []; // Listen for data available events and add the data to the buffer recorder.addEventListener('dataavailable', event => { buffer.push(event.data); }); // Listen for the stop event and create an MP4 file from the buffer recorder.addEventListener('stop', () => { const blob = new Blob(buffer, {type: 'video/mp4'}); // Create a download link and trigger a download const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'screen-recording.mp4'; a.click(); }); // Stop recording after 5 seconds setTimeout(() => { recorder.stop(); }, 100000); }); } |
As you can see we are first of all capturing the screen
and then converting it to blob
and download it as mp4 video
file as shown below