Wednesday, February 19, 2025

JavaScript, Capture screen recording and save its file

Can I create a simple program in Javascript which captures the screen recording and saves the recorded file?


Yes, you can create a simple JavaScript program to capture the screen and save the recording as a file. This can be done using the MediaDevices API to capture the screen and the MediaRecorder API to record the stream. Here’s a step-by-step guide to creating a basic screen recording program.

Step-by-Step Code Example
This example will prompt the user to select a screen or application window to record, record the stream, and save it as a .webm file.

html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Screen Recorder</title>
</head>
<body>
    <h1>Screen Recorder</h1>
    <button id="startBtn">Start Recording</button>
    <button id="stopBtn" disabled>Stop Recording</button>
    <video id="preview" controls autoplay></video>

    <script>
        let mediaRecorder;
        let recordedChunks = [];

        const startBtn = document.getElementById('startBtn');
        const stopBtn = document.getElementById('stopBtn');
        const preview = document.getElementById('preview');

        startBtn.addEventListener('click', async () => {
            // Request screen capture
            const stream = await navigator.mediaDevices.getDisplayMedia({
                video: true,
                audio: true
            });

            // Preview the screen capture in the video element
            preview.srcObject = stream;

            // Initialize MediaRecorder for the stream
            mediaRecorder = new MediaRecorder(stream, {
                mimeType: 'video/webm; codecs=vp9'
            });

            // Store recorded chunks when data is available
            mediaRecorder.ondataavailable = (event) => {
                if (event.data.size > 0) {
                    recordedChunks.push(event.data);
                }
            };

            // Handle stop event to save the recorded file
            mediaRecorder.onstop = () => {
                const blob = new Blob(recordedChunks, { type: 'video/webm' });
                const url = URL.createObjectURL(blob);

                // Download the recorded video
                const a = document.createElement('a');
                a.href = url;
                a.download = 'recorded_screen.webm';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);

                // Reset chunks for the next recording
                recordedChunks = [];
            };

            // Start recording
            mediaRecorder.start();
            startBtn.disabled = true;
            stopBtn.disabled = false;
        });

        stopBtn.addEventListener('click', () => {
            // Stop recording and screen stream
            mediaRecorder.stop();
            preview.srcObject.getTracks().forEach(track => track.stop());
            startBtn.disabled = false;
            stopBtn.disabled = true;
        });
    </script>
</body>
</html>
Explanation of the Code
HTML Structure:

We have two buttons (Start Recording and Stop Recording) and a <video> element to preview the screen recording.
JavaScript Logic:

Button Event Listeners: When the "Start Recording" button is clicked, the program:
Requests the user’s permission to capture the screen using navigator.mediaDevices.getDisplayMedia().
Creates a MediaRecorder instance to record the screen.
Sets up handlers for ondataavailable (to capture recording data in chunks) and onstop (to save the recorded video file).
Saving the Video File:
When recording stops, the captured chunks are assembled into a Blob, which is then turned into a downloadable .webm file.
Stop Recording: The "Stop Recording" button stops the MediaRecorder and terminates the screen capture stream.
Key Points to Remember
MIME Type: This example uses video/webm with VP9 codec, which is widely supported for web-based recording.
Browser Compatibility: This should work in most modern browsers that support MediaDevices and MediaRecorder APIs (e.g., Chrome, Edge, and Firefox).
Audio Capture: This example enables audio capture if available (selected in screen sharing). If you want to omit audio, set audio: false in getDisplayMedia().
This code provides a simple setup for capturing, previewing, and saving screen recordings directly from a web page using JavaScript.

No comments:

Post a Comment

Hot Topics