daw679
daw679

Reputation: 23

How do I play audio from POST response?

I'm making an ajax call to website that generates audio file for me.

    $.ajax({
        type: "POST",
        url: "http://localhost/download",
        data: "data",
        success: (response=>{
        console.log(response)
        const w = new Audio(response);
        w.play()    
    })

})

I get the response with filesize as expected (I can check it in Network tab) but when I'm trying to assign the response as a new Audio, it ends up with error

Invalid URI. Load of media resource ID3� failed.

Upvotes: 1

Views: 1152

Answers (1)

Calum
Calum

Reputation: 1889

You need to set the source of the audio after creating an ObjectURL from the blob:

$.ajax({
  type: "POST",
  url: "http://localhost/download",
  data: "data",
  success: (response) => {
    console.log(response);
    var url = window.URL.createObjectURL(response.value); //where value is the blob
    const w = new Audio();
    w.src = url;
    w.play();
  },
});

Upvotes: 1

Related Questions