How to use object url in audio src

1.1k Views Asked by At

I am making a audio player using

<audio src={audioSrc}>

tag.

When I get the audio file, it was a binary file(blob below) so I created a blob with it.

let test = new Blob(blob, {type: 'audio/mp3'};

And then created an object url

let objUrl = URL.createObjectURL(test);

This objUrl looks like blob:https://xxxxx and when I pass this string to <audio src={objUrl}/>, I cannot hear anything.

I was wondering if I have to convert this url to make it available in audio tag.

Can I get an advice for this problem please?

2

There are 2 best solutions below

1
On

Just add another prop autoplay

<audio  src={URL.createObjectURL(test)} autoplay/>
0
On

The first parameter of the Blob constructor is an array. MDN describes it like this:

An Array of ArrayBuffer, ArrayBufferView, Blob, USVString objects, or a mix of any of such objects, that will be put inside the Blob. USVString objects are encoded as UTF-8.

https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob#parameters

Maybe creating your blob like this already solves the problem:

let test = new Blob([ blob ], { type: 'audio/mp3' });

Another problem I could think of is that the binary data has a different mimeType other than 'audio/mp3' which could cause the audio element to give up decoding the data.