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.