How to Record Video on a Web Page

A simple example of how to record video on a web page using JavaScript
January 20, 2025 by
How to Record Video on a Web Page
Hamed Mohammadi
| No comments yet

Recording video directly on a web page is an incredibly useful feature for various applications, including video calls, user-generated content platforms, and online education. With modern web technologies like the MediaStream API, implementing video recording functionality has become straightforward. In this blog post, we'll guide you through the steps to record video on a web page.

Prerequisites

To follow along with this guide, you should have a basic understanding of HTML, CSS, and JavaScript. We’ll be working with the following technologies:

  • MediaStream API: To capture video from the user's camera.
  • MediaRecorder API: To record the video.

Step 1: Setting Up the HTML Structure

We’ll start by creating a simple HTML structure for the video recording interface. This will include a video element to preview the camera feed, buttons to start and stop recording, and a section to play the recorded video.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Video Recorder</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            margin: 20px;
        }
        video {
            width: 100%;
            max-width: 600px;
            margin: 10px auto;
            border: 1px solid #ccc;
        }
        button {
            margin: 5px;
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h1>Video Recorder</h1>
    <video id="preview" autoplay muted></video>
    <div>
        <button id="start">Start Recording</button>
        <button id="stop" disabled>Stop Recording</button>
    </div>
    <h2>Recorded Video</h2>
    <video id="recorded" controls></video>
    <script src="app.js"></script>
</body>
</html>


Step 2: Accessing the User's Camera

To access the user's camera, we'll use the getUserMedia method from the MediaStream API. Add the following code to a JavaScript file (e.g., app.js).

const preview = document.getElementById('preview');
const startButton = document.getElementById('start');
const stopButton = document.getElementById('stop');
const recordedVideo = document.getElementById('recorded');

let mediaRecorder;
let recordedChunks = [];

// Access the user's camera
async function startCamera() {
    try {
        const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
        preview.srcObject = stream;
        return stream;
    } catch (err) {
        console.error('Error accessing the camera:', err);
        alert('Could not access the camera. Please check your permissions.');
    }
}

startCamera();

Step 3: Recording the Video

To record the video, we use the MediaRecorder API. The recorded data will be stored in chunks, which we'll combine into a single Blob for playback.

startButton.addEventListener('click', async () => {
    const stream = await startCamera();

    mediaRecorder = new MediaRecorder(stream);
    recordedChunks = [];

    mediaRecorder.ondataavailable = (event) => {
        if (event.data.size > 0) {
            recordedChunks.push(event.data);
        }
    };

    mediaRecorder.onstop = () => {
        const blob = new Blob(recordedChunks, { type: 'video/webm' });
        const url = URL.createObjectURL(blob);
        recordedVideo.src = url;
    };

    mediaRecorder.start();
    startButton.disabled = true;
    stopButton.disabled = false;
});

stopButton.addEventListener('click', () => {
    mediaRecorder.stop();
    startButton.disabled = false;
    stopButton.disabled = true;
});

Step 4: Testing the Application

  1. Save your index.html and app.js files.
  2. Open the index.html file in a browser (you may need to use a local server due to camera access restrictions).
  3. Allow camera and microphone permissions when prompted.
  4. Click the Start Recording button to begin recording and the Stop Recording button to end it.
  5. The recorded video will appear below the buttons for playback.

Step 5: Enhancing the User Experience

Here are some ideas to make your video recorder more user-friendly:

  1. Add a Timer: Display the recording duration.
  2. Error Handling: Provide clear error messages if the user denies camera access or if the browser doesn't support required APIs.
  3. Save Recorded Video: Allow users to download the recorded video by adding a download button.
const downloadButton = document.createElement('button');
downloadButton.textContent = 'Download Video';
document.body.appendChild(downloadButton);

downloadButton.addEventListener('click', () => {
    const blob = new Blob(recordedChunks, { type: 'video/webm' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download = 'recorded-video.webm';
    document.body.appendChild(a);
    a.click();
    URL.revokeObjectURL(url);
});

Browser Compatibility

While the MediaStream and MediaRecorder APIs are supported by most modern browsers, some older versions might not support them. Always test your implementation on different browsers and provide fallback options if necessary.

Conclusion

With the MediaStream and MediaRecorder APIs, adding video recording functionality to your web page is easier than ever. This guide walked you through the basics, but there are many ways to expand and improve this feature. Whether you’re building a video chat app, an online learning platform, or a creative content tool, this functionality can significantly enhance your web application.

Have you implemented video recording on your web page? Let us know your experience or share your tips in the comments!

in Web
How to Record Video on a Web Page
Hamed Mohammadi January 20, 2025
Share this post
Tags
Archive

Please visit our blog at:

https://zehabsd.com/blog

A platform for Flash Stories:

https://readflashy.com

A platform for Persian Literature Lovers:

https://sarayesokhan.com

Sign in to leave a comment