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.
2
Answers
I think to play audio from a
Uint8Array
representing audio data in a browser, you can use the Web Audio API.I add an example code below:
This example assumes that your audio data is in a common audio format like
WAV
.You can adjust the MIME type in the Blob constructor based on your actual audio format.
To convert the ArrayBuffer back into audio and play it in a browser, you can follow these steps and use the following code example:
Here’s some example code to achieve this:
By creating a Blob from the Uint8Array and using URL.createObjectURL, you’re able to set the generated URL as the source for the audio element, allowing you to play the audio in the browser.