How to play base64 audio files on firefox using HTML5?

I am trying to encode a base64 mp3 file. Then play through the browser. It works great on safari and chrome, but not on Firefox .

My question is "is there a way to get firefox to play an audio file in base64 / binary string format?"

ps: I know that firefox cannot play mp3, so I tried other audio files like wav, ogg ... None of them work in Firefox after I encoded them to base64. Please, help

<body> <div> <form> Select a file: <input type="file" name="img" id="myaudio"/> </form> </div> <div id="click"> <span>click</span> </div> <div id="body"> <audio controls="controls" autobuffer="autobuffer" autoplay="autoplay"> </audio> </div> <script type="text/javascript"> $(document).ready(function(){ $("#click").click(function(){ var audio = $("input[type='file']").get(0).files[0]; readFile(audio, function(e) { var result = e.target.result; *// here I get a binary string of my original audio file* encodedData = btoa(result); *// encode it to base64* $("audio").html("<source src=\"data:audio/mp3;base64,"+encodedData+"\"/>"); *//add the source to audio* }); }); }); function readFile(file, onLoadCallback){ var reader = new FileReader(); reader.onload = onLoadCallback; reader.readAsBinaryString(file); } </script> </body> 
+6
source share
1 answer

Instead of using readAsBinaryString , then base64 encoding.
use readAsDataURL , which gives you the full data uri.

 <script type="text/javascript"> $(document).ready(function(){ $("#click").click(function(){ var audio = $("input[type='file']").get(0).files[0]; readFile(audio, function(e) { var result = e.target.result; *// here I get a binary string of my original audio file* //encodedData = btoa(result); *// encode it to base64* $("audio").html("<source src=\""+result+"\"/>"); *//add the source to audio* }); }); }); function readFile(file, onLoadCallback){ var reader = new FileReader(); reader.onload = onLoadCallback; reader.readAsDataURL(file); } </script> 

http://jsfiddle.net/Z9pJ7/2/

+3
source

Source: https://habr.com/ru/post/951771/


All Articles