预加载的声音是否正在卸载? [英] Pre-loaded sounds being unloaded?

查看:99
本文介绍了预加载的声音是否正在卸载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有以下测试代码:

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>

它会预加载一些音频文件,然后单击按钮,随机播放其中一个.问题是,大约一分钟后,某些音频文件似乎已卸载,因为在播放时会再次从服务器获取它们.这意味着,一旦我的应用程序"加载完毕,我仍然需要连接到互联网才能听到一些声音.如果启用了缓存,则不需要连接到Internet,但是我不能依赖于启用了缓存.有什么办法可以使这些文件保持加载状态,从而使它们不需要重复获取?

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?

推荐答案

您可以将所有媒体提取为Blob,然后从中创建blobURI.

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

这样,浏览器会将其保存在内存中(直到硬刷新或直到您调用URL.revokeObjectURL(blobURI);为止)

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

这篇关于预加载的声音是否正在卸载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆