Search code examples
javascriptweb-audio-api

AudioBuffer not cachable / decodeAudioData takes to long


I'm trying to write a custom web player for music using the Web Audio Api, but I'm running into a problem decoding the audio.

I'm fetching the .mp3 as ArrayBuffer from my backend and decode it, using the AudioContext.decodeAudioData function.

  const resp = await fetch(url);
  const raw = await resp.arrayBuffer();
  const audioBuffer = context.decodeAudioData(raw);

I'm trying to cache the AudioBuffer in an IndexedDB, but it is not clonable. The decoding takes about 10 seconds on my device with a regular mp3 and thats pretty long. Do I have any other choice to prevent long wait times between songs (apart from prefetching and "predecoding")?


Solution

  • AudioBuffer are not meant for large pieces of audio

    This interface represents a memory-resident audio asset (for one-shot sounds and other short audio clips). Its format is non-interleaved IEEE 32-bit linear PCM with a nominal range of -1 -> +1. It can contain one or more channels. Typically, it would be expected that the length of the PCM data would be fairly short (usually somewhat less than a minute). For longer sounds, such as music soundtracks, streaming should be used with the audio element and MediaElementAudioSourceNode.

    (emphasis mine)

    https://www.w3.org/TR/webaudio/#AudioBuffer

    You might want to look into MediaElementAudioSourceNode if you actually need to manipulate the audio on the fly. Otherwise a simple audio element should suffice.