Skip to main content

preloadVideo()

此函数是 @remotion/preload 包的一部分。

🌐 This function is part of the @remotion/preload package.

此函数在 DOM 中预加载视频,以便当 video 标签被挂载时,它可以立即播放。

🌐 This function preloads a video in the DOM so that when a video tag is mounted, it can play immediately.

虽然预加载对于渲染不是必要的,但它可以帮助在 <Player /> 和 Studio 中实现无缝播放。

🌐 While preload is not necessary for rendering, it can help with seamless playback in the <Player /> and in the Studio.

preloadVideo() 的一个替代方案是 prefetch() API。请参阅 @remotion/preload vs prefetch() 来决定哪一个更适合你的使用场景。

🌐 An alternative to preloadVideo() is the prefetch() API. See @remotion/preload vs prefetch() to decide which one is better for your usecase.

用法

🌐 Usage

import {preloadVideo} from '@remotion/preload';

const unpreload = preloadVideo('https://remotion.media/BigBuckBunny.mp4');

// If you want to un-preload the video later
unpreload();

它是如何运作的

🌐 How it works

  • 在 Firefox 上,它会在文档的 head 元素中附加一个 <link rel="preload" as="video"> 标签。
  • 在其他浏览器中,它会在文档的 body 元素中添加一个 <video preload="auto"> 标签。

处理重定向

🌐 Handle redirects

如果视频 URL 重定向到另一个 URL,预加载原始 URL 将无效。

🌐 If the video URL redirects to another URL, preloading the original URL does not work.

如果你包含的 URL 是未知的,请使用 resolveRedirect() 来通过编程方式获取可能重定向后的最终 URL。

🌐 If the URL you include is unknown, use resolveRedirect() to programmatically obtain the final URL following potential redirects.

如果资源不支持 CORS,resolveRedirect() 将会失败。如果资源发生重定向,并且不支持 CORS,则无法预加载该资源。

🌐 If the resource does not support CORS, resolveRedirect() will fail. If the resource redirects, and does not support CORS, you cannot preload the asset.

这段代码尝试在尽力的基础上预加载视频。如果无法解析重定向,它会尝试预加载原始 URL。

🌐 This snippet tries to preload a video on a best-effort basis. If the redirect cannot be resolved, it tries to preload the original URL.

import {preloadVideo, resolveRedirect} from '@remotion/preload';
import {OffthreadVideo} from 'remotion';

// This code gets executed immediately once the page loads
let urlToLoad = 'https://player.vimeo.com/external/291648067.hd.mp4?s=94998971682c6a3267e4cbd19d16a7b6c720f345&profile_id=175&oauth2_token_id=57447761';

resolveRedirect(urlToLoad)
  .then((resolved) => {
    // Was able to resolve a redirect, setting this as the video to load
    urlToLoad = resolved;
  })
  .catch((err) => {
    // Was unable to resolve redirect e.g. due to no CORS support
    console.log('Could not resolve redirect', err);
  })
  .finally(() => {
    // In either case, we try to preload the original or resolved URL
    preloadVideo(urlToLoad);
  });

// This code only executes once the component gets mounted
const MyComp: React.FC = () => {
  // If the component did not mount immediately, this will be the resolved URL.

  // If the component mounted immediately, this will be the original URL.
  // In that case preloading is ineffective anyway.
  return <OffthreadVideo src={urlToLoad}></OffthreadVideo>;
};

另请参阅

🌐 See also