I have a JSON object in memory with audio data stored as Uint8Array:
audioContent: { type: "Buffer", data: (361728) […] }
Basically - I'm not sure how to convert this back this into an audio stream and play it in a browser.
Approach I've tried:
<audio id="audio_player" src = ...>
<script>
let audioElement = document.getElementById("audio_player");
const blob = new Blob(trackData.audioContent.data);
const url = window.URL.createObjectURL(blob);
audioElement.src = url;
</script>
The truth is I have no proper concept of what's needed to make this work beyond the high level 'turning the array into an encoded stream'
I'm looking for code examples I can use to understand how to do this.
EDIT Thanks to all for sharing their code and suggestions. Going through the suggestions firefox wasn't happy with the encoding. I went back to square 1 - encoded the source audio as Base64 and played it like so in a JS function, with trackData being the base64 data.
var audio = new Audio("data:audio/mp3;base64," + trackData);
audio.play();
Given a json array of unsigned 8 bit integers representing audio data, initialize a Blob [mdn] with this array.
<audio id="audio_player"></audio>
<script>
let audioElement = document.getElementById("audio_player");
const blob = new Blob(trackData.audioContent.data, { type: "audio/mpeg" });
const url = window.URL.createObjectURL(blob);
audioElement.src = url;
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With