0

I am trying to find out how I can preload multiple audio files into the browser and still use them after network connection was lost (after of course initial success while preloading the files).

Preload multiple audio files

was so far my favorite method and easy to read. The code below is basically from there. But because it works with new Audio() and then audio.src in the player, the player still tries to check with the src, even after all got preloaded and i get the following error message:

GET http://xxxxx.com/sound.mp3 net::ERR_INTERNET_DISCONNECTED

Uncaught (in promise) DOMException: Failed to load because no supported source was found.

because the player (html audio with id "player") tries to play the sound like this:

function play(index) {
player.src = audioFiles[index];
player.play();
}

which uses src which in this case is a web-path. As does the preloader-function:

function preloadAudio(url)
{
  var audio = new Audio();
  // once this file loads, it will call loadedAudio()
  // the file will be kept by the browser as cache
  audio.addEventListener('canplaythrough', loadedAudio, false);
  audio.src = url;
}

I would love to make the user preload all soundfiles at once and give them the possibility to walk out of network connection while still playing the sounds.

Can i load the file while preloading into some type of object that is then referenced by the player? Is there another way to achieve this?

Community
  • 1
  • 1
gaugau
  • 765
  • 1
  • 9
  • 30

1 Answers1

0

I think as long as you don't change audio.src after the connection's lost you should be OK. So you'll need one audio element for each file you want to preload. Perhaps:

var audioPlayers = audioFiles.map( file => {
    var audio = new Audio();
    audio.src = file;
    return audio;
})
Ben West
  • 4,398
  • 1
  • 16
  • 16
  • thanks. awkward truth: i left the dev tools open and "disable cache" checked all the time and was wondering why it didn't work (-‸ლ) – gaugau Mar 31 '18 at 17:50
  • that wouldn't load entire file, it would be left for the browser to decide which parts to load and when through partial-content requests. Thus by default at least in current Chromium implementations only first 100KBs would be pre-fetched. – Vega4 Sep 27 '21 at 09:32