是否可以在不将其添加到DOM的情况下预加载和缓存视频文件? [英] Is it possible to preload and cache video files without adding them to the DOM?

查看:255
本文介绍了是否可以在不将其添加到DOM的情况下预加载和缓存视频文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一款游戏,其中涉及触发30个小视频文件中的一个,具体取决于您获得的结果。由于视频需要在用户交互后立即播放,理想情况下我希望将视频预先加载并准备就绪。

I'm working on a game that involves trigging one of 30 small video files depending on what result you get. As the videos need to play immediately after the user interacts, ideally I'd like to have the videos preloaded and ready to go.

我已经添加了PreloadJS,排队了我需要的所有资产。

I've added PreloadJS, queued up all of the assets I need.

查看网络标签在检查员中,我可以在加载屏幕上看到所有20mb的视频传输。

Looking at the Network tab in inspector, I can see all 20mb of videos transferring on the loading screen.

但是,当播放剪辑时,似乎是重新下载它们而不是从内存中播放它们......

However, when it comes time to play the clips, it seems to be re-downloading them rather than playing them from memory...

我认为一旦文件被下载,它们就会停留在浏览器缓存中,一旦我尝试加载具有相同src的文件,它就会从下载资源池中取出它,但似乎并非如此...

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...

我知道如何在不向页面添加30个视频播放器的情况下将下载的文件保存在内存中吗?

Any idea how I can keep the downloaded files in memory without adding 30 video players to the page?

谢谢!

Ger

推荐答案

您可以尝试使用Blob和Object-URL将整个文件加载到内存中。通过这种方式,非附加视频元素可以通过对象URL直接播放。

You could try to load the entire file into memory using Blob and Object-URL. This way the non-attached video element can play directly via the object-URL.

如果这是一个关于系统资源的好策略当然是你需要决定的事情你自己。

If it's a good strategy in regard to system resources is of course something you need to decide yourself.


  • 通过XHR加载 blob

  • 创建对象网址: var url =(URL || webkitURL).createObjectURL(blob);

  • Load through XHR as blob
  • Create Object 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

对象URL在生命周期中保留在内存中页。如果需要,您可以通过以下方式手动撤消它:

An object-URL is kept in memory during the life-cycle of a page. You can manually revoke it this way if needed:

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

这篇关于是否可以在不将其添加到DOM的情况下预加载和缓存视频文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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