venky
venky

Reputation: 195

converting audio file to base64 using javascript

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.

Upvotes: 9

Views: 23032

Answers (2)

joe
joe

Reputation: 5542

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.

Upvotes: 1

mido
mido

Reputation: 25034

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);
}

Upvotes: 6

Related Questions