简体   繁体   English

是否可以在不将视频文件添加到DOM的情况下预加载和缓存视频文件?

[英]Is it possible to preload and cache video files without adding them to the DOM?

I'm working on a game that involves trigging one of 30 small video files depending on what result you get. 我正在开发一款游戏,该游戏涉及根据获得的结果触发30个小视频文件之一。 As the videos need to play immediately after the user interacts, ideally I'd like to have the videos preloaded and ready to go. 由于视频需要在用户互动后立即播放,因此理想情况下,我希望将视频预加载并准备好播放。

I've added PreloadJS, queued up all of the assets I need. 我添加了PreloadJS,将我需要的所有资产排队。

Looking at the Network tab in inspector, I can see all 20mb of videos transferring on the loading screen. 查看检查器中的“网络”选项卡,我可以在加载屏幕上看到所有20mb的视频传输。

However, when it comes time to play the clips, it seems to be re-downloading them rather than playing them from memory... 但是,当需要播放剪辑时,似乎是在重新下载它们,而不是从内存中播放它们...

I thought that once the files were downloaded, they'd just stay in the browser cache, and once I tried to load a file with the same src, it would pull it from the pool of downloaded assets, but this doesn't seem to be the case... 我以为,一旦下载了文件,它们就会留在浏览器缓存中,而一旦我尝试使用相同的src加载文件,它将把它从下载的资源池中拉出来,但这似乎并没有就是这样...

Any idea how I can keep the downloaded files in memory without adding 30 video players to the page? 知道如何在不向页面添加30个视频播放器的情况下将下载的文件保存在内存中吗?

Thanks! 谢谢!

Ger GER

You could try to load the entire file into memory using Blob and Object-URL. 您可以尝试使用Blob和Object-URL将整个文件加载到内存中。 This way the non-attached video element can play directly via the object-URL. 这样,未连接的视频元素可以直接通过对象URL播放。

If it's a good strategy in regard to system resources is of course something you need to decide yourself. 如果对系统资源而言这是一个好的策略,那么您当然需要自行决定。

  • Load through XHR as blob 通过XHR作为blob加载
  • Create Object URL: var url = (URL || webkitURL).createObjectURL(blob); 创建对象URL: var url = (URL || webkitURL).createObjectURL(blob);

The video is now in memory, so when you need to play it, set it as source for the video element and you should be ready to go: 视频现在已在内存中,因此当您需要播放视频时,请将其设置为视频元素的来源,您就可以开始使用了:

var video = document.createElement("video");
video.oncanplay = ...;  // attach to DOM, invoke play() etc.
video.src = url;        // set the object URL

An object-URL is kept in memory during the life-cycle of a page. 在页面的生命周期中,对象URL被保留在内存中。 You can manually revoke it this way if needed: 您可以根据需要以这种方式手动将其撤消:

(URL || webkitURL).revokeObjectURL(url);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM