Skip to main content

<Player>

一个可以在常规 React 应用中渲染的组件(例如:Next.JSVite.jsCreate React App)用于显示 Remotion 视频。

🌐 A component which can be rendered in a regular React App (for example: Next.JS, Vite.js, Create React App) to display a Remotion video.

MyApp.tsx
import {Player} from '@remotion/player'; import {MyVideo} from './remotion/MyVideo'; export const App: React.FC = () => { return <Player component={MyVideo} durationInFrames={120} compositionWidth={1920} compositionHeight={1080} fps={30} />; };

查看更多使用示例

应用编程接口

🌐 API

componentlazyComponent

🌐 component or lazyComponent

直接传递一个 React 组件 传递一个返回动态导入的函数。两者都不传或者同时传递都是错误的。

🌐 Pass a React component in directly or pass a function that returns a dynamic import. Passing neither or both of the props is an error.

如果你使用 lazyComponent,请将其封装在 useCallback() 中以避免持续渲染。在这里查看示例。

🌐 If you use lazyComponent, wrap it in a useCallback() to avoid constant rendering. See here for an example.

note

播放器不使用 <Composition>。直接传递你的组件,不要将其封装在 <Composition> 组件中。

durationInFrames

视频的时长,以帧为单位。必须是整数且大于0。

🌐 The duration of the video in frames. Must be an integer and greater than 0.

fps

视频的帧率。必须是一个数字。

🌐 The frame rate of the video. Must be a number.

compositionWidth

你希望视频在渲染为 MP4 时的宽度。使用 style={{width: <width>}} 来定义在浏览器中假定的宽度。

note

示例: 如果你想渲染全高清(FHD)视频,请将 compositionWidth 设置为 1920,并将 compositionHeight 设置为 1080。默认情况下,播放器也会假定这些尺寸。 要使其更小,请传递一个 style 属性以为播放器提供不同的宽度:{"style={{width: 400}}"}。查看 播放器缩放 以了解更多信息。

compositionHeight

你希望视频在渲染为 MP4 时的高度。使用 style={{height: <height>}} 来定义在浏览器中应假定的高度。

inputProps

使用 component 属性将 props 传递给你指定的组件。TypeScript 定义采用了你给予 component 的 props 的形式。

🌐 Pass props to the component that you have specified using the component prop. The Typescript definition takes the shape of the props that you have given to your component.

loop?

视频结束时是否应重新开始。默认 false

🌐 Whether the video should restart when it ends. Default false.

autoPlay?

视频是否应在加载后立即开始播放。默认 false

🌐 Whether the video should start immediately after loaded. Default false.

controls?

视频是否应显示进度条和播放/暂停按钮。默认 false.

🌐 Whether the video should display a seek bar and a play/pause button. Default false.

showVolumeControls?

视频是否应该显示音量滑块和静音按钮。只有在 controls 也设置为 true 时才有效。默认值 true

🌐 Whether the video should display a volume slider and a mute button. Only has an effect if controls is also set to true. Default true.

allowFullscreen?

视频是否可以全屏。默认 true

🌐 Whether the video can go fullscreen. By default true.

clickToPlay?

一个布尔属性,用于定义是否可以通过单击播放器来播放、暂停或恢复视频。如果 controls 为真,默认值为 true,否则为 false

🌐 A boolean property defining whether you can play, pause or resume the video with a single click into the player. Default true if controls are true, otherwise false.

doubleClickToFullscreen?

一个布尔属性,定义是否可以通过双击播放器来进入全屏和退出全屏。如果启用,单击视频一次将延迟200毫秒暂停视频,以等待可能的第二次点击。默认值为 false

🌐 A boolean property defining whether you can go fullscreen and exit fullscreen in the video with double click into the player. If enabled, clicking on the video once will delay pausing the video for 200ms to wait for a possible second click. Default false.

note

此选项在移动设备上不受支持。在移动设备上,你不会通过双击来全屏显示。

spaceKeyToPlayOrPause?

一个布尔属性,定义是否可以使用空格键播放或暂停视频。如果启用,播放视频后按空格键会暂停或恢复视频播放。仅当 controls 为真时有效。默认为 true

🌐 A boolean property defining whether you can play or pause a video using space key. If enabled, playing the video and subsequently pressing the space key pauses and resumes the video. Only works if controls is true. Default true.

moveToBeginningWhenEnded?v3.1.3

一个布尔属性,用于定义视频结束后视频位置是否应回到零。仅在 loop 被禁用时有效。默认 true

🌐 A boolean property defining whether the video position should go back to zero once the video has ended. Only works if loop is disabled. Default true.

style?

HTMLDivElement 的常规 style 属性。如果你希望播放器的尺寸与原始组合尺寸不同,可以传入不同的高度和宽度。

🌐 A regular style prop for a HTMLDivElement. You can pass a different height and width if you would like different dimensions for the player than the original composition dimensions.

className?v3.1.3

要应用于容器的 HTML 类名。

🌐 A HTML class name to be applied to the container.

initialFrame?v3.1.14

从特定帧开始播放。默认 0。播放器挂载后,此属性无法更改。

🌐 Start the playback from a specific frame. Default 0. Once the player is mounted, this property cannot be changed.

numberOfSharedAudioTags?v2.3.1

如果你使用 <Html5Audio /> 标签,某些浏览器(特别是 iOS Safari)可能无法播放,这是由于浏览器的自动播放策略造成的。这就是为什么 Remotion 播放器会预先挂载一组带有静音音频的音频标签,这些音频将在用户交互时播放。然后这些音频标签可以用来播放真实音频,并且不会受到浏览器自动播放策略的限制。

🌐 If you use an <Html5Audio /> tag, it might not play in some browsers (specifically iOS Safari) due to browser autoplay policies. This is why the Remotion Player pre-mounts a set of audio tags with silent audio that get played upon user interaction. These audio tags can then be used to play real audio later and will not be subject to the autoplay policy of the browser.

此选项控制渲染多少音频标签,默认值为 5。如果挂载的音频标签数量超过可用的共享音频标签数量,将会抛出错误。

🌐 This option controls how many audio tags are being rendered, the default is 5. If you mount more audio tags than shared audio tags are available, then an error will be thrown.

如果你想选择退出此行为,你可以在挂载 Remotion 的 <Html5Audio /> 标签的同时传递 0 来挂载原生音频标签。

🌐 If you'd like to opt out of this behavior, you can pass 0 to mount native audio tags simultaneously as you mount Remotion's <Html5Audio /> tags.

一旦你设置了这个属性,你将无法再更改它,否则会抛出错误。

🌐 Once you have set this prop, you cannot change it anymore or an error will be thrown.

playbackRate?

在 -4 到 4 之间(不包括 0)的数字,用于表示播放器播放媒体的速度。

🌐 A number between -4 and 4 (excluding 0) for the speed that the Player will run the media.

2playbackRate 意味着视频播放速度是原来的两倍。0.5 的播放速度意味着视频播放速度是原来的二分之一。-1 的播放速度意味着视频倒放。请注意,媒体标签(<Audio><Video><Html5Audio><Html5Video><OffthreadVideo>)不能倒放,这是浏览器的限制。

🌐 A playbackRate of 2 means the video plays twice as fast. A playbackRate of 0.5 means the video plays twice as slow. A playbackRate of -1 means the video plays in reverse. Note that the media tags (<Audio>, <Video>, <Html5Audio>, <Html5Video>, <OffthreadVideo>) cannot be played in reverse, this is a browser limitation.

默认 1

🌐 Default 1.

errorFallback?

用于渲染自定义错误消息的回调。有关示例,请参见处理错误部分。

🌐 A callback for rendering a custom error message. See Handling errors section for an example.

renderLoading?

一个回调函数,允许你返回一个自定义的用户界面,该界面在播放器加载时显示。

🌐 A callback function that allows you to return a custom UI that gets displayed while the player is loading.

回调函数的第一个参数包含播放器在渲染时的 heightwidth

🌐 The first parameter of the callback function contains the height and width of the player as it gets rendered.


const MyApp: React.FC = () => {
  // `RenderLoading` type can be imported from "@remotion/player"
  const renderLoading: RenderLoading = useCallback(({height, width}) => {
    return (
      <AbsoluteFill style={{backgroundColor: 'gray'}}>
        Loading player ({height}x{width})
      </AbsoluteFill>
    );
  }, []);

  return <Player fps={30} component={Component} durationInFrames={100} compositionWidth={1080} compositionHeight={1080} renderLoading={renderLoading} />;
};
info

如果播放器包含使用 React Suspense 的元素,或者正在使用 lazyComponent 属性,则需要加载播放器。

renderPoster?v3.2.14

一个回调函数,允许你返回一个自定义的用户界面,该界面会覆盖在播放器上。

🌐 A callback function that allows you to return a custom UI that gets overlayed over the Player.

你可以使用属性 showPosterWhenUnplayedshowPosterWhenPausedshowPosterWhenEndedshowPosterWhenBufferingshowPosterWhenBufferingAndPaused 来控制海报的渲染时间。默认情况下,它们都是禁用的。

🌐 You can control when the poster gets rendered using the props showPosterWhenUnplayed, showPosterWhenPaused, showPosterWhenEnded, showPosterWhenBuffering and showPosterWhenBufferingAndPaused. By default, they are all disabled.

第一个参数包含播放器在被渲染时的 heightwidth

🌐 The first parameter contains the height and width of the Player as it gets rendered.


import type {RenderPoster} from '@remotion/player';
import {Player} from '@remotion/player';

const MyApp: React.FC = () => {
  const renderPoster: RenderPoster = useCallback(({height, width, isBuffering}) => {
    if (isBuffering) {
      return (
        <AbsoluteFill style={{justifyContent: 'center', alignItems: 'center'}}>
          <Spinner />
        </AbsoluteFill>
      );
    }

    return (
      <AbsoluteFill style={{backgroundColor: 'gray'}}>
        Click to play! ({height}x{width})
      </AbsoluteFill>
    );
  }, []);

  return <Player fps={30} component={Component} durationInFrames={100} compositionWidth={1080} compositionHeight={1080} renderPoster={renderPoster} showPosterWhenUnplayed />;
};

showPosterWhenUnplayed?v3.2.14

在视频处于初始状态且尚未播放时渲染海报。需要设置renderPoster()。默认值:false

🌐 Render the poster when the video is in its initial state and has not been played yet. Requires renderPoster() to be set. Default: false.

showPosterWhenPaused?v3.2.14

在视频暂停时渲染海报。虽然被认为是暂停状态,但在用户快进或快退视频时,海报不会渲染。需要设置 renderPoster()。默认值:false

🌐 Render the poster when the video is paused. Although considered a paused state, the poster will not render while the user is scrubbing through the video. Requires renderPoster() to be set. Default: false.

showPosterWhenEnded?v3.2.14

当视频结束时呈现海报。要求将 moveToBeginning 设置为 falserenderPoster() 也需要设置。默认值:false

🌐 Render the poster when the video has ended. Requires moveToBeginning to be set to false. renderPoster() to be set. Default: false.

showPosterWhenBuffering?v4.0.111

<Player> 处于缓冲状态播放时渲染海报。例如,你可以在视频中心显示一个加载动画。

🌐 Render a poster when the <Player> is in the buffering state and playing. You may for example show a spinner in the center of the video.

showPosterWhenBufferingAndPaused?v4.0.290

<Player> 处于缓冲状态暂停 时渲染海报。例如,你可以在视频中心显示一个加载动画。

🌐 Render a poster when the <Player> is in the buffering state and paused. You may for example show a spinner in the center of the video.

inFrame?v3.2.15

将播放限制为仅在某一帧之后播放。视频将从此帧开始,并在结束后移动到此位置。必须是整数,不小于 0,不大于 outFrame,且不大于 durationInFrames - 1。默认值为 null,表示视频的开头。

🌐 Limit playback to only play after a certain frame. The video will start from this frame and move to this position once it has ended. Must be an integer, not smaller than 0, not bigger than outFrame and not bigger than durationInFrames - 1. Default null, which means the beginning of the video.

outFrame?v3.2.15

将播放限制为仅在某一帧之前播放。视频将在该帧结束,并在结束后回到开头。必须为整数,不小于 1,不小于 inFrame,且不大于 durationInFrames - 1。默认值为 null,表示视频结束。

🌐 Limit playback to only play before a certain frame. The video will end at this frame and move to the beginning once it has ended. Must be an integer, not smaller than 1, not smaller than inFrame and not bigger than durationInFrames - 1. Default null, which means the end of the video.

initiallyShowControls?v3.2.24

如果为真,当播放器进入场景时,控件会闪烁。2 秒内未悬停时,控件会淡出。这与 YouTube 的做法类似,并向用户表明播放器实际上是可控制的。你也可以传入一个 number,用它可以自定义持续时间(毫秒)。默认 truev3.2.24 起可用,之前不支持。

🌐 If true, the controls flash when the player enters the scene. After 2 seconds without hover, the controls fade out. This is similar to how YouTube does it, and signals to the user that the player is in fact controllable. You can also pass a number, with which you can customize the duration in milliseconds. Default true since v3.2.24, before that unsupported.

initiallyMuted?v3.3.81

如果为真,播放器在初始状态下将被静音。如果视频必须自动播放而不管浏览器的 autoplay 政策,这非常有用。

🌐 If true, the player is muted in its initial state. This is useful if the video must autoplay regardless of the autoplay policy of the browser.

renderPlayPauseButton?v3.2.32

允许你自定义控制器的播放/暂停按钮。 必须是一个返回有效 React 元素的回调函数。

🌐 Allows you to customize the Play/Pause button of the controls.
Must be a callback function that returns a valid React element.

App.tsx
import {Player, RenderPlayPauseButton} from '@remotion/player'; import {useCallback} from 'react'; export const App: React.FC = () => { const renderPlayPauseButton: RenderPlayPauseButton = useCallback(({playing, isBuffering}) => { // Since v4.0.111, isBuffering is available if (playing && isBuffering) { return <MySpinner />; } if (playing) { return <MyPlayButton />; } return <MyPauseButton />; }, []); return <Player component={MyVideo} durationInFrames={120} compositionWidth={1920} compositionHeight={1080} fps={30} renderPlayPauseButton={renderPlayPauseButton} />; };

自 v4.0.111 起,回调中会传入一个 isBuffering 参数,如果播放器处于缓冲状态,则该参数为 true了解更多 关于播放器可能处于的播放状态。

🌐 Since v4.0.111, a isBuffering parameter is being passed in the callback which is true if the Player is in a buffer state. Learn more about the playback states a Player can be in.

自 v4.0.111 起,你可以在回调中返回 null 以回退到默认 UI。

🌐 Since v4.0.111, You can return null in the callback to fall back to the default UI.

renderFullscreenButton?v3.2.32

允许你自定义播放器控件的全屏按钮,必须返回一个有效的 React 元素。如果全屏被禁用或在浏览器中不可用,将不会渲染该按钮。

🌐 Allows you to customise the fullscreen button of the player controls, must return a valid React element. If fullscreen is disabled or not available in a browser, it will not be rendered.

import {Player, RenderFullscreenButton} from '@remotion/player';
import {useCallback} from 'react';

export const App: React.FC = () => {
  const renderFullscreenButton: RenderFullscreenButton = useCallback(({isFullscreen}) => {
    if (isFullscreen) {
      return <MinimiseButton />;
    }

    return <FullScreenButton />;
  }, []);

  return <Player component={MyVideo} durationInFrames={120} compositionWidth={1920} compositionHeight={1080} fps={30} renderFullscreenButton={renderFullscreenButton} />;
};

renderMuteButton?v4.0.188

允许你自定义控件的静音按钮,必须返回一个有效的 React 元素。 操作已禁用,你必须使用 PlayerRef 自行附加点击处理程序。 如果取消视频静音,我们建议同时设置 .setVolume(1).setMuted(false)

🌐 Allows you to customize the Mute button of the controls, must return a valid React element.
Action is disabled, you must attach click handlers yourself using the PlayerRef.
If unmuting a video, we recommend setting both .setVolume(1) and .setMuted(false).

import {Player, RenderMuteButton} from '@remotion/player';
import {useCallback} from 'react';

export const App: React.FC = () => {
  const renderMuteButton: RenderMuteButton = useCallback(({muted, volume}) => {
    const isMutedOrVolumeZero = muted || volume === 0;
    if (isMutedOrVolumeZero) {
      return <VolumeOffIcon />;
    }

    return <VolumeOnIcon />;
  }, []);

  return <Player fps={30} component={MyVideo} durationInFrames={120} compositionWidth={1920} compositionHeight={1080} renderMuteButton={renderMuteButton} />;
};

renderVolumeSliderv4.0.188

允许自定义音量滑块的实现,必须返回一个有效的 React 元素。
在此处查看默认实现 here
默认实现使音量滑块为垂直方向(isVertical),并且可以使用 Tab 键进行键盘导航(onBlurinputRef)。

🌐 Allows for a custom implementation of the volume slider, must return a valid React element.
See the default implementation here.
The default implementation makes the volume slider vertical (isVertical) and is keyboard navigateable using the Tab key (onBlur, inputRef).

App.tsx
import {useCallback} from 'react'; import {Player, type RenderVolumeSlider} from '@remotion/player'; export const App: React.FC = () => { const renderVolumeSlider: RenderVolumeSlider = useCallback(({isVertical, volume, onBlur, inputRef, setVolume}) => { return null; // Your volume slider implementation }, []); return <Player fps={30} component={MyVideo} durationInFrames={120} compositionWidth={1920} compositionHeight={1080} renderVolumeSlider={renderVolumeSlider} />; };

renderCustomControls?v4.0.418

允许你在播放器的控制栏内渲染自定义控件,位于主要播放控制和全屏按钮之间。必须返回一个有效的 React 元素或 null

🌐 Allows you to render custom controls inside the player's control bar, between the main playback controls and the fullscreen button. Must return a valid React element or null.

使用 PlayerRef 从自定义控件中访问播放器状态和控制方法。

🌐 Use a PlayerRef to access player state and control methods from within your custom controls.

有关用法和示例,请参见 自定义控件

🌐 See Custom controls for usage and examples.

alwaysShowControls?v3.3.55

如果为真,将始终显示播放器控件,即使鼠标在播放器区域之外。此设置会覆盖默认行为,默认行为是在鼠标在播放器区域内一段时间不活动后自动隐藏控件。默认值 false

🌐 If true, displays the player controls at all times even if the mouse is outside the player area. This settings override the default behavior, which automatically hides the controls after a period of mouse inactivity over the player area. Default false.

hideControlsWhenPointerDoesntMove?v4.0.124

当鼠标停留在播放器上且鼠标在 3 秒内没有活动时,会隐藏播放器控制。默认情况下,此行为已启用(true)。会尊重 alwaysShowControls 属性,这意味着如果它被设置为 true,则控制将永远不会隐藏。

🌐 Hides the player controls after 3 seconds of mouse inactivity while the mouse is over the player. By default, this behavior is enabled (true). The alwaysShowControls prop is respected, meaning, if it is set to true, then the controls will never hide.

你也可以传入一个数字来定制以毫秒为单位的隐藏延迟,默认值是 3000

🌐 You may also pass in a number to customize the hide delay in milliseconds, by default 3000.

showPlaybackRateControl?v3.3.98

如果 true,显示一个齿轮图标,允许用户更改播放速度。

🌐 If true, displays a gear icon allowing the user to change the playback rate.

你可以传入一个包含可选播放速度的数组,但不支持动态更新该列表。true[0.5, 0.8, 1, 1.2, 1.5, 1.8, 2, 2.5, 3] 的别名。

🌐 You may pass an array with the available playback rates for selection, however, updating the list dynamically is not supported. true is an alias for [0.5, 0.8, 1, 1.2, 1.5, 1.8, 2, 2.5, 3].

默认 false

🌐 Default false.

posterFillModev4.0.78

要么是 player-size(默认),要么是 composition-size

🌐 Either player-size (default) or composition-size:

  • player-size:海报将按播放器的大小呈现。如果你想要呈现例如一个固定大小的播放按钮,这将非常有用。
  • composition-size:海报将以合成的尺寸渲染,并按播放器的大小进行缩放。如果你想将视频的某个静帧渲染为海报,这非常有用。

bufferStateDelayInMillisecondsv4.0.111

在播放器进入 缓冲状态 后,它将在显示缓冲界面之前等待这一时间。
这可以防止在播放器仅短时间处于缓冲状态时出现卡顿。默认值为 300

🌐 After the Player has entered a buffer state, it will wait for this amount of time before showing the buffering UI.
This prevents jank when the Player is only in a buffering state for a short time. Default 300.

注意:

🌐 Note:

这使你能够灵活地为缓冲区状态实现自定义用户界面。

🌐 This allows you to flexibly implement custom UI for the buffer state.

overflowVisiblev4.0.173

使播放器渲染画布外的内容。如果视频中有交互元素,例如可拖动的元素,这很有用。

🌐 Makes the Player render things outside of the canvas. Useful if you have interactive elements in the video such as draggable elements.

browserMediaControlsBehaviorv4.0.221

控制当用户按下键盘上的播放/暂停按钮或使用其他控制(例如 Chrome 内置控制)时发生的情况。
有关更多信息,请参见 媒体按键行为

🌐 Controls what happens when the user presses the Play/Pause button on their keyboard or uses other controls such as Chromes built-in controls.
See Media Keys Behavior for more information.

overrideInternalClassName?v4.0.233

用于替代默认 __remotion-player 的 HTML 类名。

🌐 A HTML class name to be used in place of the default __remotion-player.

logLevel?v4.0.250

One of trace, verbose, info, warn, error.
Determines how much info is being logged to the console.

Default info.

noSuspensev4.0.271

禁用 React Suspense,这在编写测试时非常有用。

🌐 Disables React Suspense, which is useful for writing tests.

acknowledgeRemotionLicense?v4.0.253

确认 Remotion 许可证 以使控制台消息消失。

🌐 Acknowledge the Remotion License to make the console message disappear.

volumePersistenceKey?v4.0.305

一个字符串,允许你自定义用于保存和获取用户音量偏好的 localStorage 键。

🌐 A string that allows you to customize the localStorage key used for saving and retrieving the user's volume preference.

默认情况下,Remotion 使用键 "remotion.volumePreference"

🌐 By default, Remotion uses the key "remotion.volumePreference".

如果你希望将音量偏好范围限定在特定的播放器实例中,则此属性非常有用。

🌐 This prop is useful if you would like to scope the volume preference to a specific Player instance.

示例:

<Player
  component={MyVideo}
  // ... other props
  volumePersistenceKey="my-app-volume-preference"
/>

PlayerRef

你可以将一个引用附加到播放器,并以命令式方式控制它。

🌐 You may attach a ref to the player and control it in an imperative manner.

import {Player, PlayerRef} from '@remotion/player';
import {useEffect, useRef} from 'react';
import {MyComposition} from './MyComposition';

const MyComp: React.FC = () => {
  const playerRef = useRef<PlayerRef>(null);

  useEffect(() => {
    if (playerRef.current) {
      console.log(playerRef.current.getCurrentFrame());
    }
  }, []);

  return (
    <Player
      ref={playerRef}
      durationInFrames={30}
      compositionWidth={1080}
      compositionHeight={1080}
      fps={30}
      component={MyComposition}
      // Many other optional props are available.
    />
  );
};

以下方法可用于播放器引用:

🌐 The following methods are available on the player ref:

pause()

暂停视频。如果视频已经暂停,将不会发生任何事情。

🌐 Pause the video. Nothing happens if the video is already paused.

pauseAndReturnToPlayStart()v4.0.67

如果视频正在播放,请暂停它并返回视频上次播放的位置。

🌐 If the video is playing, pause it and return to the playback position where the video has last been played.

play()

播放视频。如果视频已经在播放,则不会发生任何事情。

🌐 Play the video. Nothing happens if the video is already playing.

如果你通过用户手势播放视频,请将 SyntheticEvent 作为参数传入,这样浏览器自动播放限制将不适用

🌐 If you play the video from a user gesture, pass the SyntheticEvent in as an argument so browser autoplay restrictions do not apply.

toggle()

如果视频正在播放,则暂停视频。如果视频已暂停,则播放视频。

🌐 Pauses the video if it's playing. Plays the video if it's paused.

如果你通过用户手势播放视频,请将 SyntheticEvent 作为参数传入,这样浏览器自动播放限制将不适用

🌐 If you play the video from a user gesture, pass the SyntheticEvent in as an argument so browser autoplay restrictions do not apply.

getCurrentFrame()

获取以当前帧表示的当前位置。除以你传入的 fps 就可以得到以秒为单位的时间。

🌐 Gets the current position expressed as the current frame. Divide by the fps you passed to get the time in seconds.

如果你想显示一个与播放器时间同步的组件,则必须做出特殊考虑。

isPlaying()v2.5.7

返回一个布尔值,指示视频是否正在播放。

🌐 Returns a boolean indicating whether the video is playing.

getContainerNode()v2.4.2

获取播放器的容器 HTMLDivElement。如果你想手动将监听器附加到播放器元素上,这非常有用。

🌐 Gets the container HTMLDivElement of the player. Useful if you'd like to manually attach listeners to the player element.

const playerRef = useRef<PlayerRef>(null);

useEffect(() => {
  if (!playerRef.current) {
    return;
  }
  const container = playerRef.current.getContainerNode();
  if (!container) {
    return;
  }

  const onClick = () => {
    console.log('player got clicked');
  };

  container.addEventListener('click', onClick);
  return () => {
    container.removeEventListener('click', onClick);
  };
}, []);

mute()

将视频静音。

🌐 Mutes the video.

unmute()

取消视频静音。

🌐 Unmutes the video.

getVolume()

获取视频的音量。音量的值在 0 到 1 之间,初始值为 1。

🌐 Gets the volume of the video. The volume is a value between 0 and 1 and is initially 1.

setVolume()

参数

🌐 Arguments

  • volumenumber

设置视频的音量。必须是介于 0 和 1 之间的值,否则将抛出异常。

🌐 Set the volume of the video. Must be a value between 0 and 1, otherwise an exception will be thrown.

isMuted()

返回一个布尔值,指定视频是否被静音。

🌐 Returns a boolean specifying whether the video is muted.

seekTo()

参数

🌐 Arguments

  • framenumber

将视频的位置移动到特定的帧。如果视频正在播放,它会短暂停止,然后在寻址完成后再次开始播放。

🌐 Move the position in the video to a specific frame. If the video is playing, it will pause for a brief moment, then start playing again after the seek is completed.

isFullscreen()

返回一个布尔值,表示视频当前是否正在全屏播放。

🌐 Returns a boolean whether the video is currently playing in fullscreen.

要观察全屏状态并对变化作出反应,请在全局文档上监听 fullscreenchange 事件。

🌐 To observe the fullscreen state and react to changes, listen to the fullscreenchange event on the global document.

requestFullscreen()

请求视频进入全屏。如果 allowFullscreen 属性为 false 或浏览器不支持允许播放器进入全屏,则此方法会抛出异常。

🌐 Requests the video to go to fullscreen. This method throws if the allowFullscreen prop is false or the browser doesn't support allow the player to go into fullscreen.

在 iOS 的 Safari 上,不支持全屏 API,因此播放器无法进入全屏。

🌐 On Safari on iOS, the Fullscreen API is not supported, so the Player cannot go into fullscreen.

exitFullscreen()

退出全屏模式。

🌐 Exit fullscreen mode.

getScale()v3.2.24

返回一个数字,表示内容相比于自然合成大小缩小了多少。例如,如果合成为 1920x1080,但播放器宽度为 960px,则此方法会返回 0.5

🌐 Returns a number which says how much the content is scaled down compared to the natural composition size. For example, if the composition is 1920x1080, but the player is 960px in width, this method would return 0.5.

addEventListener()

开始监听一个事件。请参阅 事件 部分以查看函数签名和可用的事件。

🌐 Start listening to an event. See the Events section to see the function signature and the available events.

removeEventListener()

停止监听事件。请查看 Events 部分以查看函数签名和可用的事件。

🌐 Stop listening to an event. See the Events section to see the function signature and the available events.

事件

🌐 Events

使用 player ref,你可以绑定事件监听器,以便在播放器的某些事件发生时收到通知。

🌐 Using a player ref, you can bind event listeners to get notified of certain events of the player.

import {CallbackListener} from '@remotion/player';
const playerRef = useRef<PlayerRef>(null);

useEffect(() => {
  if (!playerRef.current) {
    return;
  }
  const onPlay: CallbackListener<'play'> = () => {
    console.log('play');
  };
  const onRateChange: CallbackListener<'ratechange'> = (e) => {
    console.log('ratechange', e.detail.playbackRate);
  };
  const onVolumeChange: CallbackListener<'volumechange'> = (e) => {
    console.log('new volume', e.detail.volume);
  };

  const onPause: CallbackListener<'pause'> = () => {
    console.log('pausing');
  };

  const onSeeked: CallbackListener<'seeked'> = (e) => {
    console.log('seeked to ' + e.detail.frame);
  };

  const onTimeupdate: CallbackListener<'timeupdate'> = (e) => {
    console.log('time has updated to ' + e.detail.frame);
  };

  const onEnded: CallbackListener<'ended'> = () => {
    console.log('ended');
  };

  const onError: CallbackListener<'error'> = (e) => {
    console.log('error', e.detail.error);
  };

  const onFullscreenChange: CallbackListener<'fullscreenchange'> = (e) => {
    console.log('fullscreenchange', e.detail.isFullscreen);
  };

  const onScaleChange: CallbackListener<'scalechange'> = (e) => {
    console.log('scalechange', e.detail.scale);
  };

  const onMuteChange: CallbackListener<'mutechange'> = (e) => {
    console.log('mutechange', e.detail.isMuted);
  };

  playerRef.current.addEventListener('play', onPlay);
  playerRef.current.addEventListener('ratechange', onRateChange);
  playerRef.current.addEventListener('volumechange', onVolumeChange);
  playerRef.current.addEventListener('pause', onPause);
  playerRef.current.addEventListener('ended', onEnded);
  playerRef.current.addEventListener('error', onError);
  playerRef.current.addEventListener('fullscreenchange', onFullscreenChange);
  playerRef.current.addEventListener('scalechange', onScaleChange);
  playerRef.current.addEventListener('mutechange', onMuteChange);

  // See below for difference between `seeked` and `timeupdate`
  playerRef.current.addEventListener('seeked', onSeeked);
  playerRef.current.addEventListener('timeupdate', onTimeupdate);

  return () => {
    // Make sure to clean up event listeners
    if (playerRef.current) {
      playerRef.current.removeEventListener('play', onPlay);
      playerRef.current.removeEventListener('ratechange', onRateChange);
      playerRef.current.removeEventListener('volumechange', onVolumeChange);
      playerRef.current.removeEventListener('pause', onPause);
      playerRef.current.removeEventListener('ended', onEnded);
      playerRef.current.removeEventListener('error', onError);
      playerRef.current.removeEventListener('fullscreenchange', onFullscreenChange);
      playerRef.current.removeEventListener('scalechange', onScaleChange);
      playerRef.current.removeEventListener('mutechange', onMuteChange);
      playerRef.current.removeEventListener('seeked', onSeeked);
      playerRef.current.removeEventListener('timeupdate', onTimeupdate);
    }
  };
}, []);

seeked

当用户使用播放条或使用 seek() 更改时间位置时触发。你可以通过从 e.detail.frame 读取来获取当前帧。

🌐 Fired when the time position is changed by the user using the playback bar or using seek(). You may get the current frame by reading it from e.detail.frame.

playerRef.current.addEventListener('seeked', (e) => {
  console.log('seeked to ' + e.detail.frame); // seeked to 120
});

此事件会在每一帧更新时触发。如果过多的重新渲染导致速度变慢,建议改用 timeupdate 事件。

🌐 This event fires on every single frame update. Prefer the timeupdate event instead if the excessive rerenders cause slowdown.

此事件仅在寻求期间触发。如果你也想在播放过程中获取时间更新,请改用 frameupdate

🌐 This event is only fired during seeking. Use frameupdate instead if you also want to get time updates during playback.

ended

当视频结束且循环播放被禁用时触发。

🌐 Fires when the video has ended and looping is disabled.

play

当视频开始播放或从暂停恢复时触发。

🌐 Fires when the video has started playing or has resumed from a pause.

ratechange

playbackRate发生变化时触发。

🌐 Fires when the playbackRate has changed.

scalechangev3.3.86

scale 发生变化时触发。也由 getScale() 返回。

🌐 Fires when the scale has changed. Also returned by getScale().

volumechangev3.3.86

当音量发生变化时触发。也由 getVolume() 返回。

🌐 Fires when the volume has changed. Also returned by getVolume().

pause

当视频已暂停或结束时触发。

🌐 Fires when the video has paused or ended.

timeupdate

当视频播放时,会定期触发时间更新。与 seeked 事件不同,帧会被跳过,并且该事件最多每250毫秒触发一次,每秒只触发几次。

🌐 Fires periodic time updates when the video is playing. Unlike the seeked event, frames are skipped, and the event is throttled to only fire a few times a second at most every 250ms.

playerRef.current.addEventListener('timeupdate', (e) => {
  console.log('current frame is ' + e.detail.frame); // current frame is 120
});

如果你只想在跳转时获取时间更新,请优先使用 seeked 事件。

🌐 Prefer the seeked event if you only want to get time updates during seeking.

如果你需要每一帧都更新,请优先使用 frameupdate 事件。

🌐 Prefer the frameupdate event if you need an update for every single frame.

frameupdatev3.2.27

每当当前时间发生变化时触发,适用于播放和寻求期间。

🌐 Fires whenever the current time has changed, during both playback and seeking.

playerRef.current.addEventListener('frameupdate', (e) => {
  console.log('current frame is ' + e.detail.frame); // current frame is 120
});

如果你只想在跳转时获取时间更新,请优先使用 seeked 事件。

🌐 Prefer the seeked event if you only want to get time updates during seeking.

如果你只需要定期更新(最多每 250 毫秒一次),请优先选择 timeupdate 事件。

🌐 Prefer the timeupdate event if you only need periodical updates (at most every 250ms).

fullscreenchangev3.2.0

当播放器进入或退出全屏时触发。通过读取 e.detail.isFullscreen 或调用 playerRef.isFullscreen(),你可以确定播放器当前是否处于全屏状态。

🌐 Fires when the player enters or exits fullscreen. By reading e.detail.isFullscreen or calling playerRef.isFullscreen() you can determine if the player is currently in fullscreen or not.

playerRef.current.addEventListener('fullscreenchange', (e) => {
  console.log('is fullscreen' + e.detail.isFullscreen); // is fullscreen true
});

mutechangev3.3.98

当播放器的音频静音或未静音时触发。也由isMuted()返回。

🌐 Fires when the player's audio is muted or not. Also returned by isMuted().

playerRef.current.addEventListener('mutechange', (e) => {
  console.log('is mute' + e.detail.isMuted); // is mute true
});

error

当 React 组件中发生错误或未捕获的异常时触发。

🌐 Fires when an error or uncaught exception has happened in the React component.

你可能会在读取 e.detail.error 值时遇到错误:

🌐 You may get the error by reading the e.detail.error value:

ref.current?.addEventListener('error', (e) => {
  console.log('error ', e.detail.error); // error [Error: undefined is not a function]
});

waitingv4.0.111

当播放器进入 本地缓冲状态 时触发。

🌐 Fires when the Player has entered into the native buffering state.

在这里阅读如何最佳实现状态管理

🌐 Read here how to best implement state management.

resumev4.0.111

当播放器退出native buffering state时触发。

🌐 Fires when the Player has exited the native buffering state.

在这里阅读如何最佳实现状态管理

🌐 Read here how to best implement state management.

处理错误

🌐 Handling errors

由于视频是用 React 编写的,因此容易崩溃。 当视频抛出异常时,你可以使用 error 事件 来处理错误。 视频将卸载并显示错误 UI,但主应用(嵌入播放器的 React 应用)不会崩溃。 由你来处理错误并重新挂载视频(例如通过在 React 中更改 key 属性)。

🌐 Since videos are written in React, they are prone to crashing. When a video throws an exception, you may handle the error using the error event. The video will unmount and show an error UI, but the host application (The React app which is embedding the player) will not crash. It is up to you to handle the error and to re-mount the video (for example by changing the key prop in React).

此功能是使用错误边界实现的,因此只有渲染函数中的错误会被捕获。事件处理程序和异步代码中的错误不会被报告,也不会导致视频卸载。

🌐 This feature is implemented using an error boundary, so only errors in the render function will be caught. Errors in event handlers and asynchronous code will not be reported and will not cause the video to unmount.

如果视频崩溃,你可以自定义显示的错误信息:

🌐 You can customize the error message that is shown if a video crashes:


const MyApp: React.FC = () => {
  // `ErrorFallback` type can be imported from "@remotion/player"
  const errorFallback: ErrorFallback = useCallback(({error}) => {
    return (
      <AbsoluteFill
        style={{
          backgroundColor: 'yellow',
          justifyContent: 'center',
          alignItems: 'center',
        }}
      >
        Sorry about this! An error occurred: {error.message}
      </AbsoluteFill>
    );
  }, []);

  return <Player fps={30} component={Component} durationInFrames={100} compositionWidth={1080} compositionHeight={1080} errorFallback={errorFallback} />;
};

另请参阅

🌐 See also