Search code examples
javascripthtmlaudiopreload

Pre-loaded sounds being unloaded?


So, I have the following test code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
</head>
<body>
   <button onclick="play()">Play</button>
    <script>
        var sounds = new Array();
        preloadSnd = function(){
            var snds = new Array();
            for(i = 0; i < preloadSnd.arguments.length; i++){
                snds[i] = new Audio();
                snds[i].src = preloadSnd.arguments[i];
            }
            sounds.push(snds);
        }
        preloadSnd(
            "test1.mp3",
            "test2.mp3",
            "test3.mp3",
            "test4.mp3",
            "test5.mp3",
            "test6.mp3",
            "test7.mp3",
            "test8.mp3"
        )
        play = function(){
            sounds[0][parseInt(Math.random()*8)].play();
        }
    </script>
</body>
</html>

It pre-loads some audio files and on the click of a button, randomly plays one of them. The problem is, after about a minute or so, some of the audio files seem to get unloaded because they are fetched from the server again when played. This means that once my "application" has loaded, I still need to be connected to the internet to hear some of the sounds. If my cache is enabled it doesn't require connecting to the internet, but I cannot rely on the cache being enabled. Is there any way I can keep these files loaded so that they don't need to be fetched repeatedly?


Solution

  • You can fetch all your medias as Blobs, and then create blobURIs from it.

    This way, the browser will keep it in memory (until an hard refresh or until you call URL.revokeObjectURL(blobURI);)

    fetch("https://dl.dropboxusercontent.com/s/8c9m92u1euqnkaz/GershwinWhiteman-RhapsodyInBluePart1.mp3")
    .then(r => r.blob()) // could be xhr.responseType = 'blob'
    .then(blob => {
      const aud = new Audio(URL.createObjectURL(blob));
      aud.controls = true;
      document.body.appendChild(aud);
      console.log('Fully loaded and cached until the page dies...')
      });