Sling Academy
Home/JavaScript/Generate WebM or MP4 Files from Live Streams in JavaScript

Generate WebM or MP4 Files from Live Streams in JavaScript

Last updated: December 13, 2024

In modern web applications, live streaming has become a crucial feature for engaging audiences. Whether you're building a video calling app, a broadcasting platform, or a live streaming website, converting and recording live streams to video formats like WebM or MP4 is often required. JavaScript offers powerful APIs and libraries to achieve this. In this article, we'll explore how to generate WebM or MP4 files from live streams using JavaScript.

Working with MediaStreams

The core concept for handling live streams in web applications is the MediaStream API. This API allows you to capture, process, and manipulate live audio and video content. To access a live stream, we typically work with the browser's built-in capabilities to capture input:

navigator.mediaDevices.getUserMedia({ video: true, audio: true })
    .then(stream => {
        // Use the MediaStream here
    })
    .catch(error => {
        console.error("Failed to get MediaStream: ", error);
    });

This code snippet uses the getUserMedia method to request permission from the user to access their microphone and camera. Once permission is granted, you receive a MediaStream object, which can be used to record and manipulate media streams.

Recording MediaStream with MediaRecorder

Next, we need to record the MediaStream. For this, the MediaRecorder API is handy. It allows us to capture video (and audio) from a MediaStream and encode it in real-time.

const options = { mimeType: 'video/webm; codecs=vp9' };
const mediaRecorder = new MediaRecorder(stream, options);

let chunks = [];

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

mediaRecordgtart();

// Stop recording after 5 seconds and retrieve the recorded video
setTimeout(() => {
    mediaRecorder.stop();
}, 5000);

mediaRecorder.onstop = () => {
    const blob = new Blob(chunks, { type: 'video/webm' });
    const videoURL = URL.createObjectURL(blob);
    console.log('Recorded video available at: ', videoURL);
};

In this snippet, we initialize a MediaRecorder with a MediaStream and specify video/webm; codecs=vp9 as the format. As the recording progresses, the ondataavailable event handler stores recorded chunks in an array. After recording stops, we combine these chunks into a Blob and create a URL to access the file.

Options for MP4 Format

For those who require MP4 files, it's important to know that the MediaRecorder API primarily supports WebM format natively in browsers. To encode MP4 through JavaScript, you can use libraries like FFmpeg compiled to WebAssembly, such as ffmpeg.js.

const ffmpeg = require('@ffmpeg/ffmpeg');
const { createFFmpeg } = ffmpeg;

const ffmpegInstance = createFFmpeg({ log: true });
ffmpegInstance.load().then(() => {
    const blob = new Blob(chunks, { type: 'video/webm' });
    const formData = new FormData();
    formData.append('file', blob, 'input.webm');

    ffmpegInstance.FS('writeFile', 'input.webm', await fetchFile('input.webm'));

    ffmpegInstance.run('-i', 'input.webm', 'output.mp4').then(() => {
        const data = ffmpegInstance.FS('readFile', 'output.mp4');
        const mp4Blob = new Blob([data.buffer], { type: 'video/mp4' });
        const mp4VideoURL = URL.createObjectURL(mp4Blob);
        console.log('MP4 video available at: ', mp4VideoURL);
    });
});

With this method, you load the video file into a FormData object, then use FFmpeg in WebAssembly to convert the WebM file into MP4. This conversion happens entirely on the client-side without the need for a server-side component.

Conclusion

Generating WebM or MP4 files from live streams in JavaScript requires a basic understanding of the MediaStream and MediaRecorder APIs. While native MP4 encoding is not universally supported, tools like ffmpeg.js provide viable workarounds. By mastering these tools and techniques, developers can leverage browser APIs and libraries to extend their application's capabilities for recording live media streams efficiently.

Next Article: Integrate Recording Controls into Your UI via JavaScript

Previous Article: Capture Moments and Export Media with JavaScript Recording

Series: Web APIs – JavaScript Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration