Home > Enterprise >  Convert RIFF/WAVE format code to .wav audio file using JavaScript
Convert RIFF/WAVE format code to .wav audio file using JavaScript

Time:11-14

I am getting .wav audio file (Riff/Wave Format Binary Code) in response of AJAX POST METHOD, but unable to convert that code into .WAV audio file format to play it & save it at my local system.

enter image description here

Here's the $.ajax code which is responding me the "Riff/Wave Format" in response.

    $.ajax({
        url: "http://216.48.183.26/convert",
        type: "POST",
        headers: { 'Access-Control-Allow-Origin': '*' },
        contentType: "application/json",
        data: JSON.stringify({
            "text": "My Name is Usman Tahir. I am living in Lahore, Pakistan. Thank You.",
            "voice": "gabby_reading",
            "seed": 3,
            "rate": 16000
        }),

        success: function (response) {
            console.log(response);
        },

        error: function (jqXHR, textStatus, errorThrown) {
            console.log(jqXHR);
            console.log(textStatus);
            console.log(errorThrown);
        }
    });

Can anyone please share with me the "JavaScript Code" to convert that "RIFF/WAVE Binary Code" into .wav Audio File?

I tried so many ways, but unable to find the proper code to do this, will be very much thankful to all of you for putting your reply for my question.

Thanks,

Stay Blessed All.

CodePudding user response:

What you're getting back from the server is a WAV file. The problem is that jQuery isn't handling the binary response. It's converting it to a string by default.

I'd skip jQuery for this and use the browser's built-in Fetch API:

const res = await fetch('https://example.com/convert', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(/* your data */)
});

if (!res.ok) {
  throw new Error('Fetch failed!');
}

const wavFile = await res.blob();
document.querySelector('audio').src = URL.createObjectURL(wavFile);

Also, if you have any control over your server implementation, consider switching that method from POST to GET. And then, you don't have to do any of this. Simply putting the request data in the query string in your src URL would solve it.

  • Related