🎥 Make videos programmatically with React
remotion.dev/transcribe: Follow the tokens and allow playing the audio
Jonny Burger5ea207ad70b0
diff --git a/packages/convert/app/components/AudioPlayback.tsx b/packages/convert/app/components/AudioPlayback.tsxnew file mode 100644index 0000000000..75a526f860--- /dev/null+++ b/packages/convert/app/components/AudioPlayback.tsx@@ -0,0 +1,106 @@+import {createRef, useCallback, useEffect, useMemo, useRef} from 'react';+import type {Source} from '~/lib/convert-state';+import {useAudioPlayback} from '~/lib/use-audio-playback';++export const audioPlaybackRef = createRef<HTMLAudioElement>();++const getLeftPercentage = ({+ e,+ ref,+}: {+ e: React.PointerEvent<HTMLDivElement> | PointerEvent;+ ref: React.RefObject<HTMLDivElement | null>;+}) => {+ const leftFromContainer = ref.current?.getBoundingClientRect().left;+ const containerWidth = ref.current?.getBoundingClientRect().width;+ const pointerX = e.clientX;+ const pointerXFromContainer = pointerX - (leftFromContainer ?? 0);+ return (pointerXFromContainer / (containerWidth ?? 0)) * 100;+};++export const AudioPlayback: React.FC<{+ src: Source;+}> = ({src}) => {+ const ref = useRef<HTMLDivElement>(null);+ const url = useMemo(() => {+ if (src.type === 'url') {+ return src.url;+ }++ return URL.createObjectURL(src.file);+ }, [src]);++ useEffect(() => {+ return () => {+ URL.revokeObjectURL(url);+ };+ }, [url]);++ const toggle = useCallback((e: React.MouseEvent<HTMLDivElement>) => {+ e.stopPropagation();+ e.preventDefault();++ if (audioPlaybackRef.current) {+ if (audioPlaybackRef.current.paused) {+ audioPlaybackRef.current.play();+ } else {+ audioPlaybackRef.current.pause();+ }+ }+ }, []);++ const {playing, seekToPercentage} = useAudioPlayback();++ const onPointerDown = useCallback(+ (e: React.PointerEvent<HTMLDivElement>) => {+ if (!ref.current) {+ return;+ }++ const leftPercentage = getLeftPercentage({e, ref});+ seekToPercentage(leftPercentage);++ const onPointerMove = (e2: PointerEvent) => {+ const leftPercentageAgain = getLeftPercentage({e: e2, ref});+ seekToPercentage(leftPercentageAgain);+ };++ const cleanup = () => {+ ref.current?.removeEventListener('pointermove', onPointerMove);+ ref.current?.removeEventListener('pointerup', cleanup);+ };++ ref.current.addEventListener('pointermove', onPointerMove);+ ref.current.addEventListener('pointerup', cleanup);++ return () => {+ cleanup();+ };+ },+ [seekToPercentage],+ );++ return (+ <div+ ref={ref}+ className="absolute w-full h-full flex items-end justify-start p-4"+ onPointerDown={onPointerDown}+ >+ <audio ref={audioPlaybackRef} src={url} crossOrigin="anonymous" />+ <div+ onPointerDown={toggle}+ className="border-3 border-black w-14 h-14 rounded-full bg-white flex items-center justify-center cursor-pointer"+ >+ {playing ? (+ <svg className="w-5" viewBox="0 0 320 512">+ <path d="M48 64C21.5 64 0 85.5 0 112L0 400c0 26.5 21.5 48 48 48l32 0c26.5 0 48-21.5 48-48l0-288c0-26.5-21.5-48-48-48L48 64zm192 0c-26.5 0-48 21.5-48 48l0 288c0 26.5 21.5 48 48 48l32 0c26.5 0 48-21.5 48-48l0-288c0-26.5-21.5-48-48-48l-32 0z" />+ </svg>+ ) : (+ <svg viewBox="0 0 384 512" className="w-5 ml-1">+ <path d="M73 39c-14.8-9.1-33.4-9.4-48.5-.9S0 62.6 0 80L0 432c0 17.4 9.4 33.4 24.5 41.9s33.7 8.1 48.5-.9L361 297c14.3-8.7 23-24.2 23-41s-8.7-32.2-23-41L73 39z" />+ </svg>+ )}+ </div>+ </div>+ );+};diff --git a/packages/convert/app/components/AudioWaveform.tsx b/packages/convert/app/components/AudioWaveform.tsxindex 4999c847df..d8ad6ef072 100644--- a/packages/convert/app/components/AudioWaveform.tsx+++ b/packages/convert/app/components/AudioWaveform.tsx@@ -1,4 +1,5 @@import React, {useMemo} from 'react';+import {useAudioPlayback} from '~/lib/use-audio-playback';import {AMOUNT_OF_BARS} from '~/lib/waveform-visualizer';import {THUMBNAIL_HEIGHT} from './VideoThumbnail';@@ -12,13 +13,11 @@ export const AudioWaveForm: React.FC<{readonly bars: number[]}> = ({bars}) => {return p;}, [bars]);+ const {time, duration, playing} = useAudioPlayback();+ const progress = time / duration;+return (- <div- style={{- height: THUMBNAIL_HEIGHT,- }}- className="bg-slate-100 border-b-2 border-black justify-center items-center flex flex-row gap-px"- >+ <>{padded.map((bar, i) => {const height = ((bar ?? 0) / 255) * 40;@@ -27,14 +26,32 @@ export const AudioWaveForm: React.FC<{readonly bars: number[]}> = ({bars}) => {// eslint-disable-next-line react/no-array-index-keykey={i}data-notnull={bar !== null}- className="rounded bg-slate-200 inline-block w-[4px] data-[notnull=true]:bg-slate-600"+ data-playing={playing}+ data-show={progress > i / AMOUNT_OF_BARS}+ className="rounded bg-slate-200 inline-block w-[4px] data-[notnull=true]:bg-slate-600 data-[playing=true]:opacity-50 data-[show=true]:opacity-100"style={{height: Math.max(6, height),- transition: 'height 0.2s ease, color 0.2s ease',+ transition:+ 'height 0.2s ease, color 0.2s ease, opacity 0.2s ease',}}/>);})}+ </>+ );+};++export const AudioWaveformContainer: React.FC<{+ readonly children: React.ReactNode;+}> = ({children}) => {+ return (+ <div+ style={{+ height: THUMBNAIL_HEIGHT,+ }}+ className="relative bg-slate-100 border-b-2 border-black justify-center items-center flex flex-row gap-px"+ >+ {children}</div>);};diff --git a/packages/convert/app/components/ConvertProgress.tsx b/packages/convert/app/components/ConvertProgress.tsxindex 7c119179b6..d67bfa9335 100644--- a/packages/convert/app/components/ConvertProgress.tsx+++ b/packages/convert/app/components/ConvertProgress.tsx@@ -11,7 +11,7 @@ import {useAddOutputFilenameToTitle,useAddProgressToTitle,} from '~/lib/title-context';-import {AudioWaveForm} from './AudioWaveform';+import {AudioWaveForm, AudioWaveformContainer} from './AudioWaveform';import {Card} from './ui/card';import {Skeleton} from './ui/skeleton';import type {VideoThumbnailRef} from './VideoThumbnail';@@ -82,7 +82,9 @@ export const ConvertProgress: React.FC<{) : null}</>) : duration && isAudioOnly ? (- <AudioWaveForm bars={bars} />+ <AudioWaveformContainer>+ <AudioWaveForm bars={bars} />+ </AudioWaveformContainer>) : null}<div className="p-2"><div>diff --git a/packages/convert/app/components/ConvertUiSection.tsx b/packages/convert/app/components/ConvertUiSection.tsxindex 4ec1e49df8..3c3f83bf5b 100644--- a/packages/convert/app/components/ConvertUiSection.tsx+++ b/packages/convert/app/components/ConvertUiSection.tsx@@ -1,22 +1,5 @@import React, {useCallback} from 'react';--const Switch: React.FC<{- readonly active: boolean;- readonly onToggle: () => void;-}> = ({active, onToggle}) => {- return (- <div- data-active={active}- className="h-6 transition-all rounded-full w-12 border-2 bg-gray-200 p-[2px] cursor-pointer data-[active=true]:bg-brand border-black relative"- onClick={onToggle}- >- <div- data-active={active}- className="h-4 w-4 left-[2px] transition-all rounded-full bg-white border-2 border-black absolute data-[active=true]:left-[calc(100%-1rem-2px)]"- />- </div>- );-};+import {Switch} from './ui/switch';export const ConvertUiSection: React.FC<{readonly children: React.ReactNode;diff --git a/packages/convert/app/components/Main.tsx b/packages/convert/app/components/Main.tsxindex 975dbaaafd..f290a2b7bf 100644--- a/packages/convert/app/components/Main.tsx+++ b/packages/convert/app/components/Main.tsx@@ -35,7 +35,11 @@ export const Main: React.FC<{setSrc={setSrc}/>) : (- <PickFile setSrc={setSrc} title={getHeaderTitle(routeAction)} />+ <PickFile+ action={routeAction}+ setSrc={setSrc}+ title={getHeaderTitle(routeAction)}+ />)}</div><GlobalApisInConsole />diff --git a/packages/convert/app/components/PickFile.tsx b/packages/convert/app/components/PickFile.tsxindex 8e843b5239..16f28d2792 100644--- a/packages/convert/app/components/PickFile.tsx+++ b/packages/convert/app/components/PickFile.tsx@@ -1,6 +1,7 @@import React, {useCallback} from 'react';-import {SAMPLE_FILE} from '~/lib/config';+import {SAMPLE_FILE_CONVERT, SAMPLE_FILE_TRANSCRIBE} from '~/lib/config';import type {Source} from '~/lib/convert-state';+import type {RouteAction} from '~/seo';import {AlternativePickFileOptions} from './AlternativePickFileOptions';import {DropFileBox} from './DropFileBox';import {TextMarkLogo} from './TextMarkLogo';@@ -9,10 +10,17 @@ import {WhyRemotionConvert} from './WhyRemotionConvert';export const PickFile: React.FC<{readonly setSrc: React.Dispatch<React.SetStateAction<Source | null>>;readonly title: string;-}> = ({setSrc, title}) => {+ readonly action: RouteAction;+}> = ({setSrc, title, action}) => {const onSampleFile = useCallback(() => {- setSrc({type: 'url', url: SAMPLE_FILE});- }, [setSrc]);+ setSrc({+ type: 'url',+ url:+ action.type === 'transcribe'+ ? SAMPLE_FILE_TRANSCRIBE+ : SAMPLE_FILE_CONVERT,+ });+ }, [setSrc, action]);const onDrop = useCallback((event: React.DragEvent<HTMLDivElement>) => {diff --git a/packages/convert/app/components/Probe.tsx b/packages/convert/app/components/Probe.tsxindex d3c3ec0104..d3d057ebf4 100644--- a/packages/convert/app/components/Probe.tsx+++ b/packages/convert/app/components/Probe.tsx@@ -9,8 +9,9 @@ import {useCopyThumbnailToFavicon,} from '~/lib/title-context';import {useThumbnailAndWaveform} from '~/lib/use-thumbnail';+import {AudioPlayback} from './AudioPlayback';import {AudioTrackOverview} from './AudioTrackOverview';-import {AudioWaveForm} from './AudioWaveform';+import {AudioWaveForm, AudioWaveformContainer} from './AudioWaveform';import {ContainerOverview} from './ContainerOverview';import {EmbeddedImage} from './EmbeddedImage';import {SourceLabel} from './SourceLabel';@@ -135,7 +136,10 @@ export const Probe: React.FC<{{(images?.length ?? 0) > 0 ? (<EmbeddedImage images={images as MediaParserEmbeddedImage[]} />) : isAudio ? (- <AudioWaveForm bars={waveform} />+ <AudioWaveformContainer>+ <AudioWaveForm bars={waveform} />+ <AudioPlayback src={src} />+ </AudioWaveformContainer>) : null}{error ? null : thumbnailError ? null : isAudio ? null : (<VideoThumbnaildiff --git a/packages/convert/app/components/transcribe/App.tsx b/packages/convert/app/components/transcribe/App.tsxindex 65b7137477..43b8c77965 100644--- a/packages/convert/app/components/transcribe/App.tsx+++ b/packages/convert/app/components/transcribe/App.tsx@@ -13,7 +13,7 @@ const Transcribe: React.FC<{const [state, setState] = useState<TranscriptionState>({type: 'idle'});const [selectedModel, setSelectedModel] =- useState<DownloadWhisperModelParams['model']>('small.en');+ useState<DownloadWhisperModelParams['model']>('tiny.en');return (<>@@ -36,7 +36,7 @@ const Transcribe: React.FC<{state={state}setState={setState}/>- <div className="h-4" />+ {state.type === 'transcribing' ? <div className="h-4" /> : null}{state.type === 'done' || state.type === 'transcribing' ? (<Display result={state.result} />) : null}diff --git a/packages/convert/app/components/transcribe/display.tsx b/packages/convert/app/components/transcribe/display.tsxindex 5fee9d72be..5a377820f5 100644--- a/packages/convert/app/components/transcribe/display.tsx+++ b/packages/convert/app/components/transcribe/display.tsx@@ -1,29 +1,113 @@+/* eslint-disable react/no-array-index-key */import type {Caption} from '@remotion/captions';+import {useEffect, useMemo, useRef, useState} from 'react';+import {useAudioPlayback} from '~/lib/use-audio-playback';import {Card} from '../ui/card';+import {Switch} from '../ui/switch';++const SingleToken: React.FC<{+ readonly caption: Caption;+ readonly time: number;+ readonly lastActive: boolean;+}> = ({caption, time, lastActive}) => {+ const ref = useRef<HTMLDivElement>(null);+ useEffect(() => {+ if (ref.current && lastActive) {+ ref.current.scrollIntoView({behavior: 'smooth', block: 'center'});+ }+ }, [lastActive]);++ return (+ <div+ ref={ref}+ key={`${caption.text}-${caption.startMs}`}+ data-active={time * 1000 >= caption.startMs}+ className="border-b border-b-black py-2 border-l-4 border-l-transparent data-[active=true]:border-l-blue-500 data-[active=true]:font-bold"+ >+ <div className="px-3">+ <div className="text-xs font-brand font-medium">+ {(caption.startMs / 1000).toFixed(3)} -{' '}+ {(caption.endMs / 1000).toFixed(3)}+ </div>+ <p>{caption.text}</p>+ </div>+ </div>+ );+};++export default function Display({+ result: unfilteredResult,+}: {+ readonly result: Caption[];+}) {+ const {time} = useAudioPlayback();+ const [tokens, setTokens] = useState<boolean>(false);++ const result = useMemo(() => {+ return unfilteredResult.map((c): Caption => {+ const isSystem = c.text.startsWith('[_') && c.text.endsWith(']');+ if (isSystem) {+ return {+ ...c,+ text: ' ',+ };+ }++ return c;+ });+ }, [unfilteredResult]);++ const lastActiveIndex = useMemo(() => {+ // @ts-expect-error+ return result.findLastIndex((c) => time * 1000 >= c.startMs);+ }, [result, time]);-export default function Display({result}: {readonly result: Caption[]}) {if (result.length === 0) {return null;}return (- <Card>- {result.map((c) => {- return (- <div- key={`${c.text}-${c.startMs}`}- className="border-b border-b-black py-2"- >- <div className="px-3">- <div className="text-xs font-brand font-medium">- {(c.startMs / 1000).toFixed(3)} - {(c.endMs / 1000).toFixed(3)}- </div>- <p>{c.text}</p>- <p>{c.timestampMs}</p>- </div>- </div>- );- })}- </Card>+ <div>+ <div className="flex flex-row items-center">+ <div className="font-semibold tracking-tight text-ellipsis font-brand overflow-x-hidden text-xl">+ Show tokens+ </div>+ <div className="flex-1" />++ <Switch active={tokens} onToggle={() => setTokens((e) => !e)} />+ </div>+ <div className="h-4" />+ <Card className="max-h-[80vh] overflow-y-auto">+ <div data-tokens={tokens} className="data-[tokens=false]:p-4">+ {result.map((c, index) => {+ if (tokens) {+ if (c.text.trim() === '') {+ return null;+ }++ return (+ <SingleToken+ key={`${c.text}-${c.startMs}-${index}`}+ caption={c}+ time={time}+ lastActive={index === lastActiveIndex}+ />+ );+ }++ return (+ <span+ key={`${c.text}-${c.startMs}-${index}`}+ data-active={time * 1000 >= c.startMs}+ data-last-active={index === lastActiveIndex}+ className="data-[active=true]:font-bold data-[last-active=true]:text-brand"+ >+ {c.text}+ </span>+ );+ })}+ </div>+ </Card>+ </div>);}diff --git a/packages/convert/app/components/ui/switch.tsx b/packages/convert/app/components/ui/switch.tsxnew file mode 100644index 0000000000..ae178ef22a--- /dev/null+++ b/packages/convert/app/components/ui/switch.tsx@@ -0,0 +1,17 @@+export const Switch: React.FC<{+ readonly active: boolean;+ readonly onToggle: () => void;+}> = ({active, onToggle}) => {+ return (+ <div+ data-active={active}+ className="h-6 transition-all rounded-full w-12 border-2 bg-gray-200 p-[2px] cursor-pointer data-[active=true]:bg-brand border-black relative"+ onClick={onToggle}+ >+ <div+ data-active={active}+ className="h-4 w-4 left-[2px] transition-all rounded-full bg-white border-2 border-black absolute data-[active=true]:left-[calc(100%-1rem-2px)]"+ />+ </div>+ );+};diff --git a/packages/convert/app/lib/config.ts b/packages/convert/app/lib/config.tsindex ef9c0f6d08..919efd21e4 100644--- a/packages/convert/app/lib/config.ts+++ b/packages/convert/app/lib/config.ts@@ -1,3 +1,4 @@export const TEST_FAST = false;-export const SAMPLE_FILE =+export const SAMPLE_FILE_CONVERT ='https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4';+export const SAMPLE_FILE_TRANSCRIBE = 'https://parser.media/audio.wav';diff --git a/packages/convert/app/lib/use-audio-playback.ts b/packages/convert/app/lib/use-audio-playback.tsnew file mode 100644index 0000000000..16654265c8--- /dev/null+++ b/packages/convert/app/lib/use-audio-playback.ts@@ -0,0 +1,51 @@+import {useCallback, useEffect, useState} from 'react';+import {audioPlaybackRef} from '~/components/AudioPlayback';++export const useAudioPlayback = () => {+ const [playing, setPlaying] = useState(+ () => !(audioPlaybackRef.current?.paused ?? true),+ );+ const [time, setTime] = useState(0);+ const [duration, setDuration] = useState(0);++ const seekToPercentage = useCallback((percentage: number) => {+ if (!audioPlaybackRef.current) {+ return;+ }++ audioPlaybackRef.current.currentTime =+ (percentage / 100) * (audioPlaybackRef.current.duration ?? 0);+ }, []);++ useEffect(() => {+ if (!audioPlaybackRef.current) {+ return;+ }++ const onPlay = () => setPlaying(true);+ const onPause = () => setPlaying(false);+ const onTimeUpdate = () =>+ setTime(audioPlaybackRef.current?.currentTime ?? 0);+ const onDurationChange = () =>+ setDuration(audioPlaybackRef.current?.duration ?? 0);++ audioPlaybackRef.current.addEventListener('play', onPlay);+ audioPlaybackRef.current.addEventListener('pause', onPause);+ audioPlaybackRef.current.addEventListener('timeupdate', onTimeUpdate);+ audioPlaybackRef.current.addEventListener(+ 'durationchange',+ onDurationChange,+ );+ return () => {+ audioPlaybackRef.current?.removeEventListener('play', onPlay);+ audioPlaybackRef.current?.removeEventListener('pause', onPause);+ audioPlaybackRef.current?.removeEventListener('timeupdate', onTimeUpdate);+ audioPlaybackRef.current?.removeEventListener(+ 'durationchange',+ onDurationChange,+ );+ };+ }, []);++ return {playing, time, duration, seekToPercentage};+};