Pre-loaded sounds being unloaded?

眉间皱痕 提交于 2019-12-04 02:04:06

问题


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?


回答1:


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...')
  });



回答2:


Have a look at Service Workers.

OLD ANSWER:

Otherwise, did you take a look at localStorage?

Also, check out this blog post about how to store binary data in localStorage.



来源:https://stackoverflow.com/questions/45305734/pre-loaded-sounds-being-unloaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!