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

末鹿安然 提交于 2019-12-08 17:10:03

问题


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.

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

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

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

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

Thanks!

Ger


回答1:


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.

  • 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

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);


来源:https://stackoverflow.com/questions/36771463/is-it-possible-to-preload-and-cache-video-files-without-adding-them-to-the-dom

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