How to Convert Base64 to Video with JavaScript
// Convert Base64 to video and play
function base64ToVideo(base64String) {
// Remove data URL prefix if present
const base64 = base64String.replace(/^data:video\/[a-z0-9]+;base64,/, '');
// Decode Base64 to binary
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
// Create blob and video element
const blob = new Blob([bytes], { type: 'video/mp4' });
const url = URL.createObjectURL(blob);
const video = document.createElement('video');
video.src = url;
video.controls = true;
video.play();
return { video, url };
}
// Download Base64 as video file
function downloadBase64Video(base64String, filename = 'video.mp4') {
const base64 = base64String.replace(/^data:video\/[a-z0-9]+;base64,/, '');
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
const blob = new Blob([bytes], { type: 'video/mp4' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}