I have the contents of an mp3 file saved as a variable, (this isn't meant to be practical, just for a little project of mine), and I wish to play the contents of this variable as an audio file. This would be a simple task with something like node, but unfortunately I must do this entirely client side.
Please note I can not just save the content of the string as an mp3 file, I need to be able to play it from a variable.
I have looked into this, but from what I have found, it appears that this can not be done. If any of you have a solution, I would appreciate hearing it.
I have the contents of an mp3 file saved as a variable, (this isn't meant to be practical, just for a little project of mine), and I wish to play the contents of this variable as an audio file. This would be a simple task with something like node, but unfortunately I must do this entirely client side.
Please note I can not just save the content of the string as an mp3 file, I need to be able to play it from a variable.
I have looked into this, but from what I have found, it appears that this can not be done. If any of you have a solution, I would appreciate hearing it.
Share Improve this question asked May 13, 2018 at 1:36 Inigo MantoyaInigo Mantoya 6713 gold badges9 silver badges14 bronze badges 2- What sort of encoding? – CertainPerformance Commented May 13, 2018 at 1:39
- .mp3 files are plex encoded binary files, how exactly does one store that as a string in javascript? Anything can be done with enough time, but if you really have .mp3 as a string, you would probably have to read the specifications for the MP3 format, figure out how to get the header and the billions of frames that make up a pressed audio file like that. – adeneo Commented May 13, 2018 at 1:49
1 Answer
Reset to default 8This is not very practical, as you're going to get very high memory footprints within the JS engine and will likely cause unnecessary garbage collection... but it is possible to a base64 encode the MP3 which can then be fed into the src
attribute of an <audio>
tag.
Because it is unrealistically to provide a base64 encoded MP3 in an answer here I'll provide a Fiddle: https://jsfiddle/4t6bg95z/1/
But the gist of the code can be something like:
var audio = document.getElementById('audio');
audio.src = "data:audio/mp3;base64,..."; //This is a base64 encoded string of an MP3 file
window.beep = function() {
audio.play();
}
Obviously, it is much better practice to provide a URL to the audio source instead, as that's the intended usage of the Audio API.