staticFile() 遠端 URL 問題
說明 staticFile() 函式不應用於遠端 URL,以及如何正確在 Remotion 元件中使用遠端圖片和媒體資源
staticFile() 遠端 URL 問題
錯誤說明
staticFile() 函式只適用於 public/ 資料夾中的本地靜態資產,不應用於遠端 URL(以 http:// 或 https:// 開頭的網址)。
常見的錯誤寫法
import { Img, staticFile } from "remotion";
// 錯誤:不應將遠端 URL 傳入 staticFile()
const MyComp = () => {
return <Img src={staticFile("https://example.com/image.png")} />;
};staticFile() 會嘗試在 public/ 資料夾中尋找名為 https://example.com/image.png 的檔案,這顯然找不到,導致錯誤或空白圖片。
正確的寫法
遠端 URL 應直接傳入元件的 src 屬性,無需透過 staticFile():
import { Img } from "remotion";
// 正確:直接傳入遠端 URL
const MyComp = () => {
return <Img src="https://example.com/image.png" />;
};各類型媒體的正確用法
遠端圖片
import { Img } from "remotion";
const MyComp = () => {
return <Img src="https://example.com/photo.jpg" />;
};遠端影片
import { OffthreadVideo } from "remotion";
const MyComp = () => {
return (
<OffthreadVideo src="https://example.com/video.mp4" />
);
};遠端音訊
import { Audio } from "remotion";
const MyComp = () => {
return <Audio src="https://example.com/audio.mp3" />;
};動態遠端 URL(透過 Input Props)
import { Img, getInputProps } from "remotion";
const MyComp = () => {
const { imageUrl } = getInputProps();
return <Img src={imageUrl} />;
};何時使用 staticFile() vs 直接 URL
| 情境 | 正確做法 |
|---|---|
本地 public/ 資料夾中的檔案 | staticFile("filename.png") |
| 遠端 HTTP/HTTPS URL | 直接使用 URL 字串 |
| 透過 Input Props 傳入的本地檔案名 | staticFile(inputProps.filename) |
| 透過 Input Props 傳入的遠端 URL | 直接使用 inputProps.url |
使用遠端資產的注意事項
網路延遲
在渲染時,Remotion 會等待遠端資產完全載入後才進行截圖。如果網路連線較慢或資產伺服器回應時間長,可能會增加渲染時間。
建議: 若效能是關鍵考量,可以在渲染前先將資產下載到 public/ 資料夾中,改用 staticFile() 引用本地副本。
CORS 問題
在瀏覽器 Player 中使用遠端資產時,可能遇到 CORS(跨來源資源共享)問題。確保資產伺服器已設定正確的 CORS 標頭,允許您的網域存取。
快取策略
Remotion 不會自動快取遠端資產。若在多幀中多次使用同一個遠端資源,考慮在 delayRender() 中預先下載並快取資產:
import { delayRender, continueRender, Img } from "remotion";
import { useEffect, useState } from "react";
const REMOTE_URL = "https://example.com/large-image.png";
export const MyComp = () => {
const [handle] = useState(() => delayRender());
const [loaded, setLoaded] = useState(false);
useEffect(() => {
const img = new Image();
img.onload = () => {
setLoaded(true);
continueRender(handle);
};
img.src = REMOTE_URL;
}, [handle]);
if (!loaded) return null;
return <Img src={REMOTE_URL} />;
};渲染環境的網路存取
確保您的渲染環境(特別是 Lambda、Docker 容器等)能夠存取遠端資產的 URL。如果使用私有 CDN 或需要身份驗證的 URL,可能需要額外的設定。
完整範例:混合使用本地和遠端資產
import { Img, Audio, staticFile } from "remotion";
export const MyComp = () => {
return (
<div>
{/* 本地資產:使用 staticFile() */}
<Img src={staticFile("logo.png")} />
{/* 遠端資產:直接使用 URL */}
<Img src="https://cdn.example.com/background.jpg" />
{/* 本地音訊 */}
<Audio src={staticFile("background-music.mp3")} />
</div>
);
};