7

I want to convert audio file into base64 using Javascript only.

We can convert images into base64 using canvas. But how can we convert audio files.

Any help will be grateful.

AlvaroAV
  • 10,335
  • 12
  • 60
  • 91
venky
  • 175
  • 1
  • 3
  • 13
  • Why do you want it in Base64 ? Is it for transmiting or to store locally ? Also, where do you get your file from, is it from an URL or from the client's computer ? – Remy Grandin Jul 01 '15 at 12:59
  • Possible dublicate: http://stackoverflow.com/questions/21878404/how-can-i-convert-mp3-file-to-base64-encoded-string – Niddro Jul 01 '15 at 13:06
  • @RemyGrandin actually i have files in application's raw folder i want them to move to phone's local storage. – venky Jul 01 '15 at 13:25
  • I'm doing it for tizen web app.In tizen i know how to convert base64 into audio file using file system and to i can store locally.But i'm unable to convert audio file to base64. – venky Jul 01 '15 at 13:30
  • why base64? is there some kind of restriction? – Abhinav Gauniyal Jul 01 '15 at 13:32
  • Not exactly.converting file to byte array also will work.But i don't know how to do that. – venky Jul 02 '15 at 05:35
  • Possible duplicate of [How can I convert mp3 file to base64 encoded string](https://stackoverflow.com/questions/21878404/how-can-i-convert-mp3-file-to-base64-encoded-string) – vamsi Aug 21 '17 at 12:58
  • 1
    It's not duplicate actually i was asking how to do programmatically – venky Aug 22 '17 at 04:34

2 Answers2

5

you can give the below code a try, it uses btoa

function getData(audioFile, callback) {
    var reader = new FileReader();
    reader.onload = function(event) {
        var data = event.target.result.split(',')
         , decodedImageData = btoa(data[1]);                    // the actual conversion of data from binary to base64 format
        callback(decodedImageData);        
    };
    reader.readAsDataURL(audioFile);
}
mido
  • 24,198
  • 15
  • 92
  • 117
  • I am also facing the same issue to covert audio data to base64 string. @mido btoa() is for string conversion to base64 not the audio data. If you may provide the audio encoding in base64 sting will be helpful. – dinu0101 Oct 11 '17 at 09:31
0

Here's how to convert an audio file to a base64 string with JavaScript:

async function audioToBase64(audioFile) {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    reader.onerror = reject;
    reader.onload = (e) => resolve(e.target.result);
    reader.readAsDataURL(audioFile);
  });
}

You can use it like this:

<input oninput="audioToBase64(this.files[0]).then(result => console.log(result))" type="file">

This will console.log a string like data:audio/mpeg;base64,//uYxAAAAA... when a file is chosen in that filepicker.

joe
  • 3,752
  • 1
  • 32
  • 41