Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert bufferarray back into audio

Tags:

javascript

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();
like image 986
Tuds Avatar asked May 09 '26 13:05

Tuds


1 Answers

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>
like image 67
Chukwujiobi Canon Avatar answered May 11 '26 03:05

Chukwujiobi Canon