Search code examples
javascriptaudiofetchweb-audio-apiaudiocontext

Receive audio download in chunks and play smoothly with web audio API


I could not really find any way to smoothly get and play audio chunks with Web Audio API. Currently I am simply fetching an audio file from my CDN, but I have tested it on slower internet connections, and as expected it results in a long wait before the audio starts playing.

My code currently is the following:

let context = new AudioContext()
currentsrc = context.createBufferSource()

let audioBuffer = await fetch(songid)
  .then(res => res.arrayBuffer())
  .then(ArrayBuffer => context.decodeAudioData(ArrayBuffer))

currentsrc.buffer = audioBuffer
currentsrc.connect(context.destination)
currentsrc.start()

This way the script is waiting till the entire audio is downloaded which results in a break that can be long when my connection is not great. Is there any good way to download my audio in chunks and flawlessly play it with Web Audio API.

(I have seen this question and response already, I'm wondering if there's a better/cleaner way of doing this without having to separately schedule the audio chunks)


Solution

  • I later figured out that probably the best way to achieve this is to use the getReader() function of the response body, this way I can read chunks, I also gave more information as to how I finally solved this question here.