Skip to content

🎥 Make videos programmatically with React

Time display

Jonny Burgerca39c9a0cbc8
diff --git a/packages/docs/docs/player/custom-controls.mdx b/packages/docs/docs/player/custom-controls.mdx
index c2a9f82d2a..6c0cc45f75 100644
--- a/packages/docs/docs/player/custom-controls.mdx
+++ b/packages/docs/docs/player/custom-controls.mdx
@@ -40,7 +40,7 @@ Obtain a [`ref`](https://react.dev/learn/referencing-values-with-refs) of type `
### Play / Pause button
-```tsx twoslash
+```tsx twoslash title="PlayPauseButton.tsx"
import type {PlayerRef} from '@remotion/player';
import React, {SVGProps, useCallback, useEffect} from 'react';
@@ -89,3 +89,74 @@ export const PlayPauseButton: React.FC<{
:::note
The [buffering indicator](/docs/player/buffer-state) is not implemented in this snippet.
:::
+
+### Time display
+
+```tsx twoslash title="TimeDisplay.tsx"
+import type {PlayerRef} from '@remotion/player';
+import React, {useEffect} from 'react';
+
+export const formatTime = (frame: number, fps: number): string => {
+ const hours = Math.floor(frame / fps / 3600);
+
+ const remainingMinutes = frame - hours * fps * 3600;
+ const minutes = Math.floor(remainingMinutes / 60 / fps);
+
+ const remainingSec = frame - hours * fps * 3600 - minutes * fps * 60;
+ const seconds = Math.floor(remainingSec / fps);
+
+ const frameAfterSec = Math.round(frame % fps);
+
+ const hoursStr = String(hours);
+ const minutesStr = String(minutes).padStart(2, '0');
+ const secondsStr = String(seconds).padStart(2, '0');
+ const frameStr = String(frameAfterSec).padStart(2, '0');
+
+ if (hours > 0) {
+ return `${hoursStr}:${minutesStr}:${secondsStr}.${frameStr}`;
+ }
+
+ return `${minutesStr}:${secondsStr}.${frameStr}`;
+};
+
+const TimeDisplay: React.FC<{
+ durationInFrames: number;
+ fps: number;
+ playerRef: React.RefObject<PlayerRef>;
+}> = ({durationInFrames, fps, playerRef}) => {
+ const [time, setTime] = React.useState(0);
+
+ useEffect(() => {
+ const {current} = playerRef;
+ if (!current) {
+ return;
+ }
+
+ const onTimeUpdate = () => {
+ setTime(current.getCurrentFrame());
+ };
+
+ current.addEventListener('frameupdate', onTimeUpdate);
+
+ return () => {
+ current.removeEventListener('frameupdate', onTimeUpdate);
+ };
+ }, [playerRef]);
+
+ return (
+ <div
+ style={{
+ fontFamily: 'monospace',
+ }}
+ >
+ <span>
+ {formatTime(time, fps)}/{formatTime(durationInFrames, fps)}
+ </span>
+ </div>
+ );
+};
+```
+
+:::note
+The [conventional time formatting for video editors](https://github.com/remotion-dev/remotion/issues/694#issuecomment-968318664) is `hh:mm:ss.ff` where `hh` is hours, `mm` is minutes, `ss` is seconds and `ff` is frames past the second.
+:::