Skip to main content

preloadAudio()

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

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

这个函数在 DOM 中预加载音频,这样当音频标签挂载时,它可以立即播放。

🌐 This function preloads audio in the DOM so that when a audio 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.

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

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

用法

🌐 Usage

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

const unpreload = preloadAudio('https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3');

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

它是如何运作的

🌐 How it works

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

处理重定向

🌐 Handle redirects

如果音频 URL 重定向到另一个 URL,预加载原始 URL 将不起作用。

🌐 If the audio 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 audio on a best-effort basis. If the redirect cannot be resolved, it tries to preload the original URL.

import {preloadAudio, resolveRedirect} from '@remotion/preload';
import {Html5Audio} from 'remotion';

// This code gets executed immediately once the page loads
let urlToLoad = 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3';

resolveRedirect(urlToLoad)
  .then((resolved) => {
    // Was able to resolve a redirect, setting this as the audio 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
    preloadAudio(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 <Html5Audio src={urlToLoad} />;
};

另请参阅

🌐 See also