Skip to content

🎥 Make videos programmatically with React

update docs

Igor Samokhovets04dccd56f94a
diff --git a/packages/docs/docs/whisper-wasm/can-use-whisper-wasm.mdx b/packages/docs/docs/whisper-wasm/can-use-whisper-wasm.mdx
new file mode 100644
index 0000000000..4308d544dd
--- /dev/null
+++ b/packages/docs/docs/whisper-wasm/can-use-whisper-wasm.mdx
@@ -0,0 +1,98 @@
+---
+image: /generated/articles-docs-whisper-wasm-can-use-whisper-wasm.png
+title: canUseWhisperWasm()
+crumb: '@remotion/whisper-wasm'
+---
+
+# canUseWhisperWasm()
+
+Checks if the current browser environment supports running `@remotion/whisper-wasm` with a specified model. This function verifies various browser capabilities like `crossOriginIsolated`, `IndexedDB`, `navigator.storage.estimate()`, and available storage space.
+
+## Example usage
+
+```tsx twoslash
+import {canUseWhisperWasm, type WhisperWasmModel} from '@remotion/whisper-wasm';
+import {useState, useEffect} from 'react';
+
+export default function MyComponent() {
+ const [supported, setSupported] = useState<boolean | null>(null);
+ const [reason, setReason] = useState<string | undefined>(undefined);
+
+ useEffect(() => {
+ const checkSupport = async () => {
+ const modelToUse: WhisperWasmModel = 'tiny.en'; // Or any other model
+ const result = await canUseWhisperWasm(modelToUse);
+ setSupported(result.supported);
+ if (!result.supported) {
+ setReason(result.detailedReason ?? result.reason);
+ }
+ };
+
+ checkSupport();
+ }, []);
+
+ if (supported === null) {
+ return <p>Checking Whisper WASM support...</p>;
+ }
+
+ if (supported) {
+ return <p>Whisper WASM is supported!</p>;
+ }
+
+ return <p>Whisper WASM is not supported: {reason}</p>;
+}
+```
+
+## Arguments
+
+### `model`
+
+The Whisper model intended to be used. This is used to check if there's enough storage space for the model.
+Possible values: `tiny`, `tiny.en`, `base`, `base.en`, `small`, `small.en`.
+
+Refer to the `WhisperWasmModel` type exported by the package for a comprehensive list.
+
+## Return value
+
+A `Promise` that resolves to a `CanUseWhisperWasmResult` object with the following properties:
+
+### `supported`
+
+A boolean indicating whether Whisper WASM can be used. `true` if supported, `false` otherwise.
+
+### `reason?`
+
+If `supported` is `false`, this field provides a brief, categorized reason for the lack of support.
+
+Possible values values include:
+
+- `window-undefined`: `window` object is not available.
+- `not-cross-origin-isolated`: The page is not cross-origin isolated.
+- `indexed-db-unavailable`: IndexedDB is not available.
+- `navigator-storage-unavailable`: `navigator.storage.estimate()` API is not available.
+- `invalid-model-name`: The provided model name is not valid.
+- `quota-undefined`: Storage quota could not be determined.
+- `usage-undefined`: Storage usage could not be determined.
+- `not-enough-space`: Insufficient storage space for the specified model.
+- `error-estimating-storage`: An error occurred while trying to estimate storage.
+
+### `detailedReason?`
+
+If `supported` is `false`, this field may contain a more detailed, human-readable explanation of why Whisper WASM is not supported.
+
+## Important considerations
+
+- **Cross-Origin Isolation:** For `SharedArrayBuffer` to work, which is required by `@remotion/whisper-wasm`, the page must be served with specific HTTP headers:
+
+ - `Cross-Origin-Opener-Policy: same-origin`
+ - `Cross-Origin-Embedder-Policy: require-corp`
+ Ensure your server is configured to send these headers. See [MDN documentation on `crossOriginIsolated`](https://developer.mozilla.org/en-US/docs/Web/API/Window/crossOriginIsolated) for more details.
+
+- **Browser Compatibility:** While this function checks for necessary APIs, always test on your target browsers as support for WebAssembly, IndexedDB, and storage estimation can vary.
+
+## See also
+
+- [Source code for `canUseWhisperWasm()`](https://github.com/remotion-dev/remotion/blob/main/packages/whisper-wasm/src/can-use-whisper-wasm.ts)
+- [`@remotion/whisper-wasm`](/docs/whisper-wasm)
+- [`transcribe()`](/docs/whisper-wasm/transcribe)
+- [`downloadWhisperModel()`](/docs/whisper-wasm/download-whisper-model)
diff --git a/packages/docs/docs/whisper-wasm/index.mdx b/packages/docs/docs/whisper-wasm/index.mdx
index 4a0ccd32e3..81fcf8edbc 100644
--- a/packages/docs/docs/whisper-wasm/index.mdx
+++ b/packages/docs/docs/whisper-wasm/index.mdx
@@ -12,39 +12,52 @@ import {TableOfContents} from './whisper-wasm';
## Example usage
-```tsx twoslash title="app.tsx"
-import {downloadWhisperModel, transcribe} from '@remotion/whisper-wasm';
-import {useEffect, useState} from 'react';
+```tsx twoslash
+import {useState} from 'react';
+import {transcribe, canUseWhisperWasm, resampleTo16Khz, downloadWhisperModel, type WhisperWasmModel} from '@remotion/whisper-wasm';
-export default function Home() {
- const [downloadProgress, setDownloadProgress] = useState(0);
- const [transcriptionProgress, setTranscriptionProgress] = useState(0);
- const [text, setText] = useState('');
+export default function MyApp() {
+ const [text, setText] = useState<string | null>(null);
- useEffect(() => {
- downloadWhisperModel({model: 'tiny.en', onProgress: setDownloadProgress});
- }, []);
+ const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
+ const file = event.target.files?.[0];
+ if (!file) return;
- const onTranscribeChunk = (start: string, end: string, text: string) => {
- console.log(`transcribed ${text} for time ${start} to ${end}`)
+ setText('Processing...');
+
+ const modelToUse: WhisperWasmModel = 'tiny.en';
+
+ const {supported, detailedReason, reason} = await canUseWhisperWasm(modelToUse);
+ if (!supported) {
+ setText(`Whisper WASM is not supported in this environment: ${detailedReason}`);
+ return;
+ }
+
+ setText('Downloading model...');
+ await downloadWhisperModel({
+ model: modelToUse,
+ onProgress: (p) => setText(`Downloading model (${Math.round(p * 100)}%)...`),
+ });
+
+ setText('Resampling audio...');
+ const channelWaveform = await resampleTo16Khz({
+ file,
+ onProgress: (p) => setText(`Resampling audio (${Math.round(p * 100)}%)...`),
+ });
+
+ setText('Transcribing...');
+ const {transcription} = await transcribe({
+ channelWaveform,
+ model: modelToUse,
+ onProgress: (p) => setText(`Transcribing (${Math.round(p * 100)}%)...`),
+ });
+ setText(transcription.map((t) => t.text).join(' '));
};
return (
<div>
- <input
- type="file"
- accept=".wav"
- onChange={(e) =>
- e.target.files &&
- transcribe({
- file: e.target.files[0],
- onProgress: setTranscriptionProgress,
- onTranscribeChunk
- }).then((result) => console.log(result))
- }
- />
-
- <progress value={transcriptionProgress} max={100} />
+ <input type="file" accept="audio/*" onChange={handleFileChange} />
+ {text && <p>{text}</p>}
</div>
);
}
diff --git a/packages/docs/docs/whisper-wasm/resample-to-16khz.mdx b/packages/docs/docs/whisper-wasm/resample-to-16khz.mdx
new file mode 100644
index 0000000000..f728b9b744
--- /dev/null
+++ b/packages/docs/docs/whisper-wasm/resample-to-16khz.mdx
@@ -0,0 +1,46 @@
+---
+image: /generated/articles-docs-whisper-wasm-resample-to-16khz.png
+title: resampleTo16Khz()
+crumb: '@remotion/whisper-wasm'
+---
+
+# resampleTo16Khz()
+
+Processes an audio `File` or `Blob` by decoding it, converting it to mono, and resampling it to a 16kHz `Float32Array`. This prepares the audio data for use with the [`transcribe()`](/docs/whisper-wasm/transcribe) function.
+
+This function operates in a browser environment as it relies on the Web Audio API (`AudioContext`, `OfflineAudioContext`) and `FileReader`.
+
+## Arguments
+
+### `file`
+
+The audio `File` or `Blob` object that you want to process. The function will attempt to decode the audio from common formats (e.g., WAV, MP3, Ogg) supported by the browser's Web Audio API.
+
+### `onProgress?`
+
+A callback function that receives progress updates during the resampling process. The `progress` value is a number between 0 and 1, where 0 indicates the start and 1 indicates completion.
+
+### `logLevel?`
+
+Default: `info`
+
+**Type:** `'trace' | 'verbose' | 'info' | 'warn' | 'error'`
+
+Optional. Determines the level of detail for logs printed to the console during the resampling process. Useful for debugging.
+
+## Return value
+
+`Promise<Float32Array>`
+
+This array contains the raw audio waveform data for a single channel (mono), sampled at 16kHz. This output is ready to be passed to the `channelWaveform` argument of the [`transcribe()`](/docs/whisper-wasm/transcribe) function.
+
+## Behavior notes
+
+- **Browser environment:** This function is intended for use in a browser environment due to its reliance on Web Audio APIs (`AudioContext`, `OfflineAudioContext`) and `FileReader`.
+- **Audio decoding:** It uses the browser's built-in audio decoding capabilities. The range of supported audio formats may vary slightly between browsers.
+- **Output format:** The output is always a mono `Float32Array` at 16kHz, regardless of the input file's original channel count or sample rate.
+
+## See also
+
+- [`transcribe()`](/docs/whisper-wasm/transcribe)
+- [`@remotion/whisper-wasm`](/docs/whisper-wasm)
diff --git a/packages/docs/docs/whisper-wasm/transcribe.mdx b/packages/docs/docs/whisper-wasm/transcribe.mdx
index fc8756ef42..b415cadf37 100644
--- a/packages/docs/docs/whisper-wasm/transcribe.mdx
+++ b/packages/docs/docs/whisper-wasm/transcribe.mdx
@@ -6,52 +6,69 @@ crumb: '@remotion/whisper-wasm'
# transcribe()
-Transcribes a media file by utilizing Whisper.cpp.
-
-```tsx twoslash title="app.tsx"
-import {useState} from 'react';
-import {transcribe} from '@remotion/whisper-wasm';
-
-export default function MyApp() {
- const [text, setText] = useState('');
-
- return (
- <input
- type="file"
- accept=".wav"
- onChange={(e) =>
- e.target.files &&
- transcribe({
- file: e.target.files[0],
- }).then((result) => console.log(result))
- }
- />
- );
-}
-```
+Transcribes pre-processed audio data (a `Float32Array` waveform) using WebAssembly-compiled `whisper.cpp`, returning the transcription. To transcribe an audio file, you first need to process it using [`resampleTo16Khz()`](/docs/whisper-wasm/resample-to-16khz).
## Arguments
-### `file`
+### `channelWaveform`
+
+A `Float32Array` representing the mono audio waveform data, resampled to 16kHz. This is typically obtained by calling [`resampleTo16Khz()`](/docs/whisper-wasm/resample-to-16khz) with an audio `File` or `Blob`.
+
+### `model`
+
+The Whisper model to use for transcription (e.g., `'tiny.en'`, `'base'`, `'small'`). This determines the size, speed, and accuracy of the model. Ensure the model has been downloaded using [`downloadWhisperModel()`](/docs/whisper-wasm/download-whisper-model) before calling `transcribe`.
+
+Possible values: `tiny`, `tiny.en`, `base`, `base.en`, `small`, `small.en`.
+
+For a list of available model names, refer to the `WhisperModel` type exported by the package or the models supported by `downloadWhisperModel()`.
+
+### `language?`
+
+default: `'auto'`
+
+Optional. The language of the audio in ISO 639-1 format (e.g., `'en'`, `'es'`, `'de'`). Set to `'auto'` for automatic language detection by Whisper.
-The audio file you want extract text from. The file has to be a 16KHz wav file.
+Possible values: `Afrikaans`, `Albanian`, `Amharic`, `Arabic`, `Armenian`, `Assamese`, `Azerbaijani`, `Bashkir`, `Basque`, `Belarusian`, `Bengali`, `Bosnian`, `Breton`, `Bulgarian`, `Burmese`, `Castilian`, `Catalan`, `Chinese`, `Croatian`, `Czech`, `Danish`, `Dutch`, `English`, `Estonian`, `Faroese`, `Finnish`, `Flemish`, `French`, `Galician`, `Georgian`, `German`, `Greek`, `Gujarati`, `Haitian`, `Haitian Creole`, `Hausa`, `Hawaiian`, `Hebrew`, `Hindi`, `Hungarian`, `Icelandic`, `Indonesian`, `Italian`, `Japanese`, `Javanese`, `Kannada`, `Kazakh`, `Khmer`, `Korean`, `Lao`, `Latin`, `Latvian`, `Letzeburgesch`, `Lingala`, `Lithuanian`, `Luxembourgish`, `Macedonian`, `Malagasy`, `Malay`, `Malayalam`, `Maltese`, `Maori`, `Marathi`, `Moldavian`, `Moldovan`, `Mongolian`, `Myanmar`, `Nepali`, `Norwegian`, `Nynorsk`, `Occitan`, `Panjabi`, `Pashto`, `Persian`, `Polish`, `Portuguese`, `Punjabi`, `Pushto`, `Romanian`, `Russian`, `Sanskrit`, `Serbian`, `Shona`, `Sindhi`, `Sinhala`, `Sinhalese`, `Slovak`, `Slovenian`, `Somali`, `Spanish`, `Sundanese`, `Swahili`, `Swedish`, `Tagalog`, `Tajik`, `Tamil`, `Tatar`, `Telugu`, `Thai`, `Tibetan`, `Turkish`, `Turkmen`, `Ukrainian`, `Urdu`, `Uzbek`, `Valencian`, `Vietnamese`, `Welsh`, `Yiddish`, `Yoruba`, `Zulu`.
+Or their corresponding ISO 639-1 codes:
+`af`, `am`, `ar`, `as`, `az`, `ba`, `be`, `bg`, `bn`, `bo`, `br`, `bs`, `ca`, `cs`, `cy`, `da`, `de`, `el`, `en`, `es`, `et`, `eu`, `fa`, `fi`, `fo`, `fr`, `gl`, `gu`, `ha`, `haw`, `he`, `hi`, `hr`, `ht`, `hu`, `hy`, `id`, `is`, `it`, `ja`, `jw`, `ka`, `kk`, `km`, `kn`, `ko`, `la`, `lb`, `ln`, `lo`, `lt`, `lv`, `mg`, `mi`, `mk`, `ml`, `mn`, `mr`, `ms`, `mt`, `my`, `ne`, `nl`, `nn`, `no`, `oc`, `pa`, `pl`, `ps`, `pt`, `ro`, `ru`, `sa`, `sd`, `si`, `sk`, `sl`, `sn`, `so`, `sq`, `sr`, `su`, `sv`, `sw`, `ta`, `te`, `tg`, `th`, `tk`, `tl`, `tr`, `tt`, `uk`, `ur`, `uz`, `vi`, `yi`, `yo`, `zh`, or `'auto'`.
+
+For a list of supported language codes, refer to the official Whisper documentation or the `WhisperLanguage` type exported by the package.
### `onProgress?`
-Act upon transcription progress. This is the function signature:
+Optional. Act upon transcription progress. The `progress` value is a number between 0 and 1.
```tsx twoslash
+// @noErrors
+// ---cut---
const onProgress = (progress: number) => {
- // do something
+ console.log(`Transcription progress: ${Math.round(progress * 100)}%`);
};
```
+### `onTranscribedChunks?`
+
+Callback function that receives an array of `TranscriptionItemWithTimestamp` objects as transcription segments are processed. This is useful for displaying live transcription updates.
+
### `threads?`
-The number of threads to use for transcription, set to `8` by default.
+The number of threads to use for transcription. Defaults to `4`. Using more threads can speed up transcription but increases CPU usage. The maximum allowed is 16; requests for more will be rejected.
+
+### `logLevel?`
+
+Default: `info`
+
+**Type:** `'trace' | 'verbose' | 'info' | 'warn' | 'error'`
+
+Determines how much info is being logged to the console.
+
+## Concurrency
+
+**Important Note:** The `transcribe()` function cannot be called multiple times concurrently. If you attempt to start a new transcription while one is already in progress, the new call will be rejected with an error. Ensure that a transcription process is complete or has been robustly handled before starting a new one.
## See also
-- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/whisper-wasm/src/helpers.ts)
+- [Source code for `transcribe()`](https://github.com/remotion-dev/remotion/blob/main/packages/whisper-wasm/src/transcribe.ts)
+- [`resampleTo16Khz()`](/docs/whisper-wasm/resample-to-16khz)
- [`@remotion/whisper-wasm`](/docs/whisper-wasm)
- [`downloadWhisperModel()`](/docs/whisper-wasm/download-whisper-model)
diff --git a/packages/docs/docs/whisper-wasm/whisper-wasm.tsx b/packages/docs/docs/whisper-wasm/whisper-wasm.tsx
index 606a2dbfee..da50d820d6 100644
--- a/packages/docs/docs/whisper-wasm/whisper-wasm.tsx
+++ b/packages/docs/docs/whisper-wasm/whisper-wasm.tsx
@@ -6,6 +6,16 @@ export const TableOfContents: React.FC = () => {
return (
<div>
<Grid>
+ <TOCItem link="/docs/whisper-wasm/can-use-whisper-wasm">
+ <strong>canUseWhisperWasm()</strong>
+ <div>Check if the browser supports Whisper WASM</div>
+ </TOCItem>
+ <TOCItem link="/docs/whisper-wasm/resample-to-16khz">
+ <strong>resampleTo16khz()</strong>
+ <div>
+ Prepare an audio file for transcription by resampling it to 16kHz
+ </div>
+ </TOCItem>
<TOCItem link="/docs/whisper-wasm/download-whisper-model">
<strong>downloadWhisperModel()</strong>
<div>Download a Whisper model in browser</div>
diff --git a/packages/docs/sidebars.js b/packages/docs/sidebars.js
index 1b74d9aab9..4b9d722cca 100644
--- a/packages/docs/sidebars.js
+++ b/packages/docs/sidebars.js
@@ -722,6 +722,8 @@ module.exports = {
items: [
'whisper-wasm/download-whisper-model',
'whisper-wasm/transcribe',
+ 'whisper-wasm/resample-to-16khz',
+ 'whisper-wasm/can-use-whisper-wasm',
],
},
{