Skip to main content

我如何使合成的时长与我的视频相同?

如果你有一个渲染视频的组件:

🌐 If you have a component rendering a video:

MyComp.tsx
import React from 'react'; import {OffthreadVideo, staticFile} from 'remotion'; export const MyComp: React.FC = () => { return <OffthreadVideo src={staticFile('video.mp4')} />; };

如果你想让合成的时长与视频相同,首先将视频源作为 React 属性:

🌐 and you want to make the composition the same duration as the video, first make the video source a React prop:

MyComp.tsx
import React from 'react'; import {OffthreadVideo, staticFile} from 'remotion'; type MyCompProps = { src: string; }; export const MyComp: React.FC<MyCompProps> = ({src}) => { return <OffthreadVideo src={src} />; };

然后,定义一个calculateMetadata()函数,根据视频计算作品的时长。
如有必要,安装@remotion/media-parser

🌐 Then, define a calculateMetadata() function that calculates the duration of the composition based on the video.
Install @remotion/media-parser if necessary.

MyComp.tsx
import {CalculateMetadataFunction} from 'remotion'; import {parseMedia} from '@remotion/media-parser'; export const calculateMetadata: CalculateMetadataFunction<MyCompProps> = async ({props}) => { const {slowDurationInSeconds, dimensions} = await parseMedia({ src: props.src, fields: { slowDurationInSeconds: true, dimensions: true, }, }); if (dimensions === null) { // For example when passing an MP3 file: throw new Error('Not a video file'); } const fps = 30; return { durationInFrames: Math.floor(slowDurationInSeconds * fps), fps, width: dimensions.width, height: dimensions.height, }; };
note

如果你的资源未启用 CORS,你可以使用 @remotion/media-utils 中的 getVideoMetadata 函数来代替 parseMedia()

最后,将 calculateMetadata 函数传递给 Composition 组件,并将先前硬编码的 src 定义为默认属性:

🌐 Finally, pass the calculateMetadata function to the Composition component and define the previously hardcoded src as a default prop:

Root.tsx
import React from 'react'; import {Composition} from 'remotion'; import {MyComp, calculateMetadata} from './MyComp'; export const Root: React.FC = () => { return ( <Composition id="MyComp" component={MyComp} durationInFrames={300} fps={30} width={1920} height={1080} defaultProps={{ src: 'https://remotion.media/BigBuckBunny.mp4', }} calculateMetadata={calculateMetadata} /> ); };

我如何使作品的时长与我的音频相同?

🌐 How do I make the composition the same duration as my audio?

遵循相同的步骤,但不是使用 parseMedia(),而是使用来自 @remotion/media-utilsgetAudioDurationInSeconds() 来根据音频文件计算作品的持续时间。

🌐 Follow the same steps, but instead of parseMedia(), use getAudioDurationInSeconds() from @remotion/media-utils to calculate the duration of the composition based on the audio file.

另请参阅

🌐 See Also