skip to Main Content

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


  1. 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:

    <audio id="audio_player" controls></audio>
    
    <script>
      // Assuming trackData.audioContent.data is your Uint8Array
      const audioData = trackData.audioContent.data;
      const arrayBuffer = audioData.buffer;
    
      // Create a Blob from the ArrayBuffer
      const blob = new Blob([arrayBuffer], { type: 'audio/wav' }); // Adjust the MIME type based on your audio format
    
      // Create a URL for the Blob
      const url = URL.createObjectURL(blob);
    
      const audioElement = document.getElementById('audio_player');
      audioElement.src = url;
      audioElement.play();
    </script>
    

    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.

    Login or Signup to reply.
  2. To convert the ArrayBuffer back into audio and play it in a browser, you can follow these steps and use the following code example:

    1. Create a Blob from the ArrayBuffer data.
    2. Create a URL for the Blob object.
    3. Set the URL as the source for the audio element.

    Here’s some example code to achieve this:

    // assuming trackData contains your JSON object with audio data
    let audioElement = document.getElementById("audio_player");
    
    let uint8Array = new Uint8Array(trackData.audioContent.data);
    let blob = new Blob([uint8Array], { type: 'audio/mpeg' });
    
    let url = URL.createObjectURL(blob);
    audioElement.src = url;
    
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search