Search code examples
javascriptaudiodownloadbase64mp3

How to download audio base64 string as an mp3 file without corrupting it?


I have a 10 second audio stream that is encoded as a base64 string. When attached to an audio tag, it plays properly inside the HTML element. On trying to download it, it downloads as a (corrupted?) file with a duration of 0:00.

var audio = document.getElementById('audio-element');
var linkTag = document.getElementById('link-element');

linkTag.href = audio.src;
linkTag.download = 'audio-file';
linkTag.click();
<!DOCTYPE html>
<html>
  <head>
      
  </head>
  <body>
    <audio src="data:audio/mp3; codecs=opus;base64,GkXfo59ChoEBQveBAULy.............IiT5Q==" controls id="audio-element">
      Your browser does not support the audio element
    </audio>
    
    <a href="" id="link-element">Download audio</a>
  </body>
</html>

The base64 string in the code snippet above is invalid, because going over the 30,000 character limit is not allowed in questions. Consequently, I had to trim it down. The original string is valid and plays fine, but can't be posted here because of the character limit.

What I want is for an accurate mp3 file to be downloaded from a base64 encoded string of type 'audio/mp3'.

How do I do this using plain javascript / ES6? Insights would be greatly appreciated.


Solution

  • audio/mp3; codecs=opus;
    

    There's no such thing. Opus is an audio codec. MP3 is an audio codec. An "MP3 file" is just a raw MPEG stream. You can't put Opus in an raw MPEG stream.

    The browser is probably being nice to you and interpreting whatever data you actually have as whatever it's actually supposed to be. Other players, probably not so much.