9

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.

8
  • 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 ? Commented Jul 1, 2015 at 12:59
  • Possible dublicate: stackoverflow.com/questions/21878404/… Commented Jul 1, 2015 at 13:06
  • @RemyGrandin actually i have files in application's raw folder i want them to move to phone's local storage. Commented Jul 1, 2015 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. Commented Jul 1, 2015 at 13:30
  • 1
    It's not duplicate actually i was asking how to do programmatically Commented Aug 22, 2017 at 4:34

2 Answers 2

6

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.