Open In App

Screen Recording with Mic Audio using JavaScript

Last Updated : 31 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Javascript is a standard technology which is used to maintain the interactivity of a web page. Not only in web interaction but also with media recording options. Yes of course this article is about Javascript’s media recording ability as per the title.

Creating a screen recorder with JavaScript (including mic audio)

getDisplayMedia: It is used to capture the user’s display. When we call this function, the user has been prompted to select the portion that should be captured. If it is rejected by the user you may experience a NotAllowedError. But if it is allowed by the user, it returns a promise that is resolved to a MediaStream object. This function can be accessed through the navigator object.

Syntax:

  • constraints:
{video: {mediaSource:"screen"}, audio: true} 

Video’s mediaSource is set to screen and recording system sound is set to true if needed. You can also set it to false if there is no need to record the system audio.

navigator.mediaDevices.getDisplayMedia(constraints)

Here the parameter constraints are known as the options that are used to capture the user display in a developer’s preferred mode where you can see the usage of constraints in the constraints section.

getUserMedia: It is used to receive the audio from the mic in our case but it can be used to access mic, webcam, etc. though getDisplayMedia() and getUserMedia() that will prompt the user for the permission and returns a promise which is resolved to a MediaStream object. And these functions can be accessed through the navigator object.

Syntax:

  • constraints:
{video:false,audio:true}

Recording video is set to true if there is a need to record the webcam, in our case it’s false. And recording mic audio is set to true if there is a need to record the mic.

navigator.mediaDevices.getUserMedia(constraints)

Here the parameter constraints are known as the options that are used to capture the user display in a developer’s preferred mode you can see the usage of constraints in the constraints section.

MediaRecorder constructor: It is used to record the MediaStream provided by the getDisplayMedia() and getUserMedia() functions.

Parameters:

  • A MediaStream provided by getUserMedia and getDisplayMedia

Syntax:

let recorder = new MediaRecorder(combine);

MediaStream constructor: It is used to store several audios and video tracks. But in our case, we use this to combine our audio and the captured video which contains the user’s screen movements into a single media stream so that we can record both display and mic at the same time.

Syntax:

// Multiple tracks can be added to the MediaStream
// object in an array format
let combine  = new MediaStream([tracks])

Example:

index.html




<html>
  
<head>
    <meta charset="UTF-8" />
  
    <link rel="stylesheet" type="text/css" 
          href="styles.css" />
    <title>Screen Recording with client 
          side javascript</title>
</head>
  
<body>
    <div style="float: left">
        <video class="recording" autoplay muted width="500px" 
               height="500px"></video>
    </div>
    <div>
        <h1>OUTPUT</h1>
        <video class="output" autoplay controls width="500px" 
               height="500px"></video>
  
        <button class="start-btn">Start Recording</button>
        <button class="stop-btn">Stop Recording</button>
        <a href="#" download="output.mp4" 
           class="download-anc">Download</a>
    </div>
    <script src="script.js"></script>
</body>


Here a video tag with a class name .recording is used to display the captured video. And we have muted it and the reason is to do is to avoid unwanted sound at the time of recording the audio from the mic. And we have also added an autoplay attribute that helps us to play the video without any user interaction like a real-time screen recorder. The video tag with the class name .output is used to display the recorded output of the video by providing a way for the user to control it, download the video with help of default controls provided by the browsers.

Now the buttons with class name .start-btn and .stop-btn is used to start and stop the recording when it is clicked with the help of javascript that you will be to see that in the script.js file.

script.js




var video = document.querySelector('.recording');
var output = document.querySelector('.output');
var start = document.querySelector('.start-btn');
var stop = document.querySelector('.stop-btn');
var anc = document.querySelector(".download-anc")
var data = [];
  
// In order record the screen with system audio
var recording = navigator.mediaDevices.getDisplayMedia({
    video: {
        mediaSource: 'screen',
    },
    audio: true,
})
    .then(async (e) => {
  
        // For recording the mic audio
        let audio = await navigator.mediaDevices.getUserMedia({ 
            audio: true, video: false })
  
        // Assign the recorded mediastream to the src object 
        video.srcObject = e;
  
        // Combine both video/audio stream with MediaStream object
        let combine = new MediaStream(
            [...e.getTracks(), ...audio.getTracks()])
  
        /* Record the captured mediastream
           with MediaRecorder constructor */
        let recorder = new MediaRecorder(combine);
  
        start.addEventListener('click', (e) => {
  
            // Starts the recording when clicked
            recorder.start();
            alert("recording started")
  
            // For a fresh start
            data = []
        });
  
        stop.addEventListener('click', (e) => {
  
            // Stops the recording  
            recorder.stop();
            alert("recording stopped")
        });
  
        /* Push the recorded data to data array 
          when data available */
        recorder.ondataavailable = (e) => {
            data.push(e.data);
        };
  
        recorder.onstop = () => {
  
            /* Convert the recorded audio to 
               blob type mp4 media */
            let blobData = new Blob(data, { type: 'video/mp4' });
  
            // Convert the blob data to a url
            let url = URL.createObjectURL(blobData)
  
            // Assign the url to the output video tag and anchor 
            output.src = url
            anc.href = url
        };
    });


Output:

You can record your entire screen or a specific application that has been opened by you or a specific chrome tab. Here we have set our constraints to object audio property {video:{mediaSource:”screen”}, audio: true} is set to true so that we have an option to Share system audio in the prompt if there is a need to record the system audio you can tick the checkbox and now click the share button to start capturing your screen in our case we have selected to capture our entire screen.

Now you can see the captured screen displayed by the video tag with real-time movements. Here you can see that the video tag that is used to display the recorded output is blank because we didn’t start our recording. After clicking the start recording button and this should start recording your screen and your mic/system audio in the background. Now just do what is all the stuff you need. Eg: play your games, explain your programming tutorials, etc. and click the stop recording button when you need to stop. After clicking the stop button you will be able to see the recorded output in the output video tag.

Now you can play the recorded output with the help of the browser’s default controls. You can also give the option to the users to download the video for browsers that don’t have a download option in their video player.

Note: Click the download link after stopping the recording.

Now you will be able to see that an output.mp4 file is downloaded and yes now you can share your recorded video to your friends, family, social media, etc.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads