preloadAudio()
此函数是 @remotion/preload
包的一部分。
此函数在 DOM 中预加载音频,以便在挂载音频标签时可以立即播放。
虽然预加载对于渲染不是必需的,但它可以帮助在 <Player />
和 Studio 中实现无缝播放。
preloadAudio()
的替代方案是 prefetch()
API。查看 @remotion/preload
vs prefetch()
来决定哪个更适合您的用例。
用法
tsx
import {preloadAudio } from "@remotion/preload";constunpreload =preloadAudio ("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3");// If you want to un-preload the audio laterunpreload ();
tsx
import {preloadAudio } from "@remotion/preload";constunpreload =preloadAudio ("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3");// If you want to un-preload the audio laterunpreload ();
工作原理
- 在 Firefox 上,它会在文档的 head 元素中附加一个
<link rel="preload" as="audio">
标签。 - 在其他浏览器上,它会在文档的 body 元素中附加一个
<audio preload="auto">
标签。
处理重定向
如果音频 URL 重定向到另一个 URL,则无法预加载原始 URL。
如果您包含的 URL 是未知的,请使用 resolveRedirect()
来以编程方式获取遵循潜在重定向的最终 URL。
如果资源不支持 CORS,resolveRedirect()
将失败。如果资源重定向,并且不支持 CORS,则无法预加载该资产。
此代码片段尝试尽最大努力预加载音频。如果无法解析重定向,则尝试预加载原始 URL。
tsx
import {preloadAudio ,resolveRedirect } from "@remotion/preload";import {Audio } from "remotion";// This code gets executed immediately once the page loadsleturlToLoad = "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 loadurlToLoad =resolved ;}).catch ((err ) => {// Was unable to resolve redirect e.g. due to no CORS supportconsole .log ("Could not resolve redirect",err );}).finally (() => {// In either case, we try to preload the original or resolved URLpreloadAudio (urlToLoad );});// This code only executes once the component gets mountedconstMyComp :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 <Audio src ={urlToLoad }></Audio >;};
tsx
import {preloadAudio ,resolveRedirect } from "@remotion/preload";import {Audio } from "remotion";// This code gets executed immediately once the page loadsleturlToLoad = "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 loadurlToLoad =resolved ;}).catch ((err ) => {// Was unable to resolve redirect e.g. due to no CORS supportconsole .log ("Could not resolve redirect",err );}).finally (() => {// In either case, we try to preload the original or resolved URLpreloadAudio (urlToLoad );});// This code only executes once the component gets mountedconstMyComp :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 <Audio src ={urlToLoad }></Audio >;};