How to Convert Base64 to Audio with JavaScript
// Convert Base64 to audio and play
function base64ToAudio(base64String) {
// Remove data URL prefix if present
const base64 = base64String.replace(/^data:audio\/[a-z]+;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 audio element
const blob = new Blob([bytes], { type: 'audio/mpeg' });
const url = URL.createObjectURL(blob);
const audio = new Audio(url);
audio.play();
return { audio, url };
}
// Download Base64 as audio file
function downloadBase64Audio(base64String, filename = 'audio.mp3') {
const base64 = base64String.replace(/^data:audio\/[a-z]+;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: 'audio/mpeg' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}