Search code examples
javascripthtmlblobarraybuffer

Convert ArrayBuffer of wav file to Blob


I'm trying to fetch from the server an audio wav file, and play it in the client with the element.

<audio id="recording" src="..." />`

I got the data as ArrayBuffer, and im trying to convert it to blob so I can change the src of the element

This is the code:

fetch("http://localhost:8080/", requestOptions)
    .then( (response) => {
        return response.arrayBuffer()
    }).then( (data) => {
        let a = new Blob([data], {type : 'audio/wav'});
        document.getElementById("recording").src = a;
    })
    .catch(error => console.error( error));

But there is an error:

GET chrome-extension://goohbjdkcejkkochpdellmjkkdpfngph/[object%20Blob] net::ERR_FILE_NOT_FOUND

It seams I didn't create the Blob properly

How can I create the blob and pass it to the <audio ... /> element?


Solution

  • You have to create an actual URL from your blob. And don't forget to revoke it afterward to free the resources.

    let blob = new Blob([data], {type : 'audio/wav'});
    const url = URL.createObjectURL(blob);
    document.getElementById("recording").src = url;
    URL.revokeObjectURL(url);