Record Audio and Video From a Webcam Using Javascript

By: Miguel
Record Audio and Video From a Webcam Using Javascript

This is a supplemental blog post to the video on how to record audio and video from a webcam using the MediaStream Recording API. This API is closely affiliated with the Media Capture and Streams API and the WebRTC API.

There is not an elaborate setup for this code since it is only a frontend application. We will have more improvements to this code shortly, including how to save the video to a server.

Developer Getting Started

Run the following commands in your terminal to prepare for coding.

mkdir record_audio_and_video_with_javascript
cd record_audio_and_video_with_javascript
touch index.html style.css

I did not put the JavaScript code into its own .js file for easier readability. I did put the css code into its own file in order to not add clutter to the index.html file.

You can clone the GitHub repository at https://github.com/coding-with-miguel/record_audio_and_video_with_javascript.

Process to Record Audio and Video From a Webcam

Open index.html in your web browser. The following command is useful for macOS.

open index.html
  • You will be asked to allow access to the camera and microphone, so click the “Start Camera” button.
  • Click the “Allow” button.
  • Click the “Start Recording” button to start recording.
  • Click the “Stop Recording” button to stop recording.
  • Click the “Download Video” link to download the recorded video and play it back.

Code Explanation

The video has the best explanation of the code, but I wanted to jot down some quick notes that will make explaining the code a little easier.

JavaScript Notes

The JavaScript is the meat of the code.

We start off by assigning variables to the HTML elements. This will allow us to use the JavaScript variable later instead of always having to use the long dot-notation version of each element. We also set some default values.

let camera_button = document.querySelector("#start-camera");
let video = document.querySelector("#video");
let start_button = document.querySelector("#start-record");
let stop_button = document.querySelector("#stop-record");
let download_link = document.querySelector("#download-video");

let camera_stream = null;
let media_recorder = null;
let blobs_recorded = [];

Now, we set up an Event Listener to the click event of the “Start Camera” button to perform an action once the button is clicked. We set up a promise to wait for the acceptance of the permission request to the user’s audio and video. If something goes wrong, we catch the error and let the user know.

camera_button.addEventListener('click', async function() {
    try {
        camera_stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
    }
    catch(error) {
        alert(error.message);
        return;
    }

We will then assign the stream to the VIDEO object, hide the “Start Camera” button, and unhide the VIDEO object and the “Start Recording” button.

    video.srcObject = camera_stream;
    camera_button.style.display = 'none';
    video.style.display = 'block';
    start_button.style.display = 'block';
});

We will also set up other Event Listeners to listen for the clicking of the other buttons.

        start_button.addEventListener('click', function() {
            media_recorder = new MediaRecorder(camera_stream, { mimeType: 'video/webm' });

            media_recorder.addEventListener('dataavailable', function(e) {
                blobs_recorded.push(e.data);
            });

            media_recorder.addEventListener('stop', function() {
                let video_local = URL.createObjectURL(new Blob(blobs_recorded, { type: 'video/webm' }));
                download_link.href = video_local;

                stop_button.style.display = 'none';
                download_link.style.display = 'block';
            });

            media_recorder.start(1000);

            start_button.style.display = 'none';
            stop_button.style.display = 'block';
        });

        stop_button.addEventListener('click', function() {
            media_recorder.stop();
        });

CSS Notes

This is very basic styling code, and can look a lot better, but I kept it extremely basic. You can definitely pretty things up quite a bit.

HTML Notes

There is not much going on inside of the BODY of the code. There are a few buttons, an anchor tag, and a VIDEO element. Some of the elements are shown/hidden by the JavaScript along the way.

What’s Next?

Now that we are able to record audio and video from a webcam, we will surely want to do something with this file. You can use it to record your own videos if you would like, but you can also use it in an application to allow users to record their own audio and video. You can then upload that content to your server for future use. That will be coming soon.