Skip to content

Instantly share code, notes, and snippets.

@mauro1998
Created November 5, 2024 00:50
Show Gist options
  • Save mauro1998/77b08218926c15a4b4e8afb400d753a9 to your computer and use it in GitHub Desktop.
Save mauro1998/77b08218926c15a4b4e8afb400d753a9 to your computer and use it in GitHub Desktop.
POC how to use MediaRecorder API to record and download an HTML video
/** Simple function to record and download an html video using MediaRecorder API */
async function downloadVideoFromBlob(
video,
duration,
filename = "recorded-video.mp4"
) {
if (!video || video.tagName !== "VIDEO") {
console.error("Please provide a valid video element.");
return;
}
// Pause and reset the video to the start
video.currentTime = 0;
video.pause();
try {
// Create a media stream from the video element
const stream = video.captureStream();
const mediaRecorder = new MediaRecorder(stream);
const chunks = [];
// Collect recorded chunks of data
mediaRecorder.ondataavailable = (event) => {
if (event.data.size > 0) {
chunks.push(event.data);
}
};
// Play the video and start recording
await video.play();
mediaRecorder.start();
// If a custom duration is given, stop recording after custom duration
if (duration) {
setTimeout(() => mediaRecorder.stop(), duration);
} else {
// Otherwise, stop recording after the video ends
video.addEventListener("ended", () => mediaRecorder.stop(), {
once: true,
});
}
// Handle the stop event to create and download the blob
mediaRecorder.onstop = () => {
const recordedBlob = new Blob(chunks, { type: "video/mp4" });
const downloadUrl = URL.createObjectURL(recordedBlob);
const a = document.createElement("a");
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
// Clean up the created URL to free up memory
URL.revokeObjectURL(downloadUrl);
};
} catch (error) {
console.error("Error capturing video:", error);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment