Open source CapCut alternative.
TypeScript
feat(site): pick the spoken language for Cut voice generation
David Le1e6dd0311a93
diff --git a/site/src/cut/components/AudioPanel.tsx b/site/src/cut/components/AudioPanel.tsxindex 0238316b..cbae1917 100644--- a/site/src/cut/components/AudioPanel.tsx+++ b/site/src/cut/components/AudioPanel.tsx@@ -31,7 +31,7 @@ import { useEditor } from "@/cut/lib/store";import { formatTime } from "@/cut/lib/time";import { NoCreditsError, synthesizeSpeech } from "@/cut/lib/tts";import { DUCK_DEFAULT } from "@/cut/lib/voiceover";-import { useSpeakerVoice, VoicePicker } from "@/cut/components/VoicePicker";+import { useSpeakerVoice, useSpeechLanguage, VoicePicker } from "@/cut/components/VoicePicker";import { cn } from "@/lib/utils";/** Starting points for the direction prompt — picking one fills the input so@@ -104,6 +104,7 @@ function sectionLabel(text: string) {function VoiceGenerator({ projectId }: { projectId: string }) {const voice = useSpeakerVoice();+ const language = useSpeechLanguage();const [script, setScript] = useState("");const [direction, setDirection] = useState("");const [busy, setBusy] = useState(false);@@ -133,6 +134,7 @@ function VoiceGenerator({ projectId }: { projectId: string }) {const { asset } = await synthesizeSpeech(projectId, [{ text, at: 0 }], {voice,direction,+ language,name: `AI voice — ${lead}`,});const cur = useEditor.getState();diff --git a/site/src/cut/components/VoicePicker.tsx b/site/src/cut/components/VoicePicker.tsxindex 59cb9b48..ba087720 100644--- a/site/src/cut/components/VoicePicker.tsx+++ b/site/src/cut/components/VoicePicker.tsx@@ -1,48 +1,67 @@"use client";import { useEffect, useRef, useState, useSyncExternalStore } from "react";-import { Captions, ChevronDown, Loader2, Pause, Play } from "lucide-react";+import { Captions, ChevronDown, Languages, Loader2, Pause, Play } from "lucide-react";import { Button } from "@/components/ui/button";import { creditsUrl, signInUrl, useSignedIn } from "@/cut/lib/generate";import { useEditor } from "@/cut/lib/store";-import { NoCreditsError, resolveVoice, speechSampleUrl, SPEECH_VOICES } from "@/cut/lib/tts";+import {+ NoCreditsError,+ resolveLanguage,+ resolveVoice,+ speechSampleUrl,+ SPEECH_LANGUAGES,+ SPEECH_VOICES,+} from "@/cut/lib/tts";import { generateSubtitlesReadout } from "@/cut/lib/voiceover";-const VOICE_KEY = "cut-tts-voice";--// One shared speaker-voice preference for every surface that generates audio-// (Audio tab, Subtitles tab, clip settings). Module-level so all mounted-// pickers stay in sync; persisted so it survives reloads.-let currentVoice: string | null = null;-const listeners = new Set<() => void>();--function readVoice(): string {- if (currentVoice === null) {- currentVoice = resolveVoice(- typeof window === "undefined" ? undefined : (localStorage.getItem(VOICE_KEY) ?? undefined)- );- }- return currentVoice;-}--function writeVoice(id: string) {- currentVoice = resolveVoice(id);- try {- localStorage.setItem(VOICE_KEY, currentVoice);- } catch {- // Preference only.- }- listeners.forEach((l) => l());+// Shared speech preferences (speaker voice, spoken language) for every surface+// that generates audio (Audio tab, Subtitles tab, clip settings). Module-level+// so all mounted pickers stay in sync; persisted so they survive reloads.+function preference(key: string, resolve: (wanted?: string) => string) {+ let current: string | null = null;+ const listeners = new Set<() => void>();+ return {+ read(): string {+ if (current === null) {+ current = resolve(+ typeof window === "undefined" ? undefined : (localStorage.getItem(key) ?? undefined)+ );+ }+ return current;+ },+ write(id: string) {+ current = resolve(id);+ try {+ localStorage.setItem(key, current);+ } catch {+ // Preference only.+ }+ listeners.forEach((l) => l());+ },+ subscribe(l: () => void) {+ listeners.add(l);+ return () => {+ listeners.delete(l);+ };+ },+ };}-function subscribe(l: () => void) {- listeners.add(l);- return () => listeners.delete(l);-}+const voicePref = preference("cut-tts-voice", resolveVoice);+const languagePref = preference("cut-tts-language", resolveLanguage);/** The shared speaker voice; every generation surface reads this. */export function useSpeakerVoice(): string {- return useSyncExternalStore(subscribe, readVoice, () => resolveVoice(undefined));+ return useSyncExternalStore(voicePref.subscribe, voicePref.read, () => resolveVoice(undefined));+}++/** The shared spoken language ("auto" = match the text); every generation+ * surface reads this. */+export function useSpeechLanguage(): string {+ return useSyncExternalStore(languagePref.subscribe, languagePref.read, () =>+ resolveLanguage(undefined)+ );}/**@@ -58,6 +77,7 @@ export function VoicePicker({title?: string;}) {const voice = useSpeakerVoice();+ const language = useSpeechLanguage();const signedOut = useSignedIn() === false;const [sampling, setSampling] = useState<null | "loading" | "playing">(null);const sampler = useRef<HTMLAudioElement | null>(null);@@ -80,7 +100,7 @@ export function VoicePicker({}const seq = ++sampleSeq.current;setSampling("loading");- speechSampleUrl(voice)+ speechSampleUrl(voice, language).then((url) => {if (seq !== sampleSeq.current) return;el.src = url;@@ -122,7 +142,7 @@ export function VoicePicker({<selectclassName="voice-select w-full appearance-none truncate rounded-lg border border-input bg-transparent py-2 pr-8 pl-2.5 text-[12.5px] outline-none focus:border-ring"value={voice}- onChange={(e) => writeVoice(e.target.value)}+ onChange={(e) => voicePref.write(e.target.value)}>{SPEECH_VOICES.map((v) => (<option key={v.id} value={v.id}>@@ -133,6 +153,28 @@ export function VoicePicker({<ChevronDown className="pointer-events-none absolute top-1/2 right-2.5 size-4 -translate-y-1/2 text-muted-foreground" /></div></div>+ <div className="flex items-center gap-2">+ <span+ className="grid size-8 shrink-0 place-items-center rounded-full bg-muted text-muted-foreground"+ title="Spoken language"+ >+ <Languages className="size-3.5" />+ </span>+ <div className="relative min-w-0 flex-1">+ <select+ className="voice-language w-full appearance-none truncate rounded-lg border border-input bg-transparent py-2 pr-8 pl-2.5 text-[12.5px] outline-none focus:border-ring"+ value={language}+ onChange={(e) => languagePref.write(e.target.value)}+ >+ {SPEECH_LANGUAGES.map((l) => (+ <option key={l.id} value={l.id}>+ {l.label}+ </option>+ ))}+ </select>+ <ChevronDown className="pointer-events-none absolute top-1/2 right-2.5 size-4 -translate-y-1/2 text-muted-foreground" />+ </div>+ </div></div>);}@@ -150,6 +192,7 @@ export function GenerateSubtitlesAudio({label?: string;}) {const voice = useSpeakerVoice();+ const language = useSpeechLanguage();const signedOut = useSignedIn() === false;const [busy, setBusy] = useState(false);const [error, setError] = useState<{ text: string; credits?: boolean } | null>(null);@@ -162,7 +205,7 @@ export function GenerateSubtitlesAudio({setBusy(true);setError(null);try {- await generateSubtitlesReadout(voice, { cueIds });+ await generateSubtitlesReadout(voice, { cueIds, language });} catch (e) {setError(e instanceof Errordiff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex f498099c..a808ae6e 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -375,6 +375,7 @@ export async function runAiTool(typeof input.direction === "string" && input.direction.trim()? input.direction.trim(): undefined,+ language: typeof input.language === "string" ? input.language : undefined,duck: isNum(input.duck) ? clamp(input.duck, 0, 1) : undefined,});const sel = useEditor.getState().selection;@@ -545,6 +546,7 @@ async function synthesizeAndPlace(const { asset, offset } = await synthesizeSpeech(projectId, segments, {voice,direction,+ language: typeof input.language === "string" ? input.language : undefined,name,});const cur = useEditor.getState();diff --git a/site/src/cut/lib/tts.ts b/site/src/cut/lib/tts.tsindex f22c1f75..92b97849 100644--- a/site/src/cut/lib/tts.ts+++ b/site/src/cut/lib/tts.ts@@ -59,6 +59,64 @@ export const SPEECH_VOICES: SpeechVoice[] = [export const DEFAULT_VOICE = "Puck";+export interface SpeechLanguage {+ id: string;+ label: string;+ /** Voice-picker sample line, written natively in the language. */+ sample: string;+}++// Sample lines stay full declarative sentences — "Hey!"-style leads make the+// TTS model intermittently return an empty clip. Change with care and re-check+// reliability across voices.+const SAMPLE_TEXT = "This is how I sound. Let's make something worth remembering.";++/** Languages the speech model speaks (BCP-47, fixed by the model). "auto" lets+ * the model match the text; a concrete pick pins pronunciation and picks the+ * sample line's language. */+export const SPEECH_LANGUAGES: SpeechLanguage[] = [+ { id: "auto", label: "Auto — match the text", sample: SAMPLE_TEXT },+ { id: "ar-EG", label: "Arabic", sample: "هذا هو صوتي. لنصنع شيئًا يستحق التذكر." },+ { id: "bn-BD", label: "Bengali", sample: "আমার কণ্ঠ এমনই শোনায়। চলুন মনে রাখার মতো কিছু তৈরি করি।" },+ { id: "nl-NL", label: "Dutch", sample: "Zo klink ik. Laten we iets maken dat het onthouden waard is." },+ { id: "en-US", label: "English", sample: SAMPLE_TEXT },+ { id: "en-IN", label: "English (India)", sample: SAMPLE_TEXT },+ { id: "fr-FR", label: "French", sample: "Voici comment je sonne. Créons quelque chose d'inoubliable." },+ { id: "de-DE", label: "German", sample: "So klinge ich. Lass uns etwas Unvergessliches schaffen." },+ { id: "hi-IN", label: "Hindi", sample: "मेरी आवाज़ ऐसी है। चलिए कुछ यादगार बनाते हैं।" },+ { id: "id-ID", label: "Indonesian", sample: "Seperti inilah suara saya. Mari membuat sesuatu yang layak dikenang." },+ { id: "it-IT", label: "Italian", sample: "Questa è la mia voce. Creiamo qualcosa che valga la pena ricordare." },+ { id: "ja-JP", label: "Japanese", sample: "これが私の声です。記憶に残るものを作りましょう。" },+ { id: "ko-KR", label: "Korean", sample: "제 목소리는 이렇습니다. 기억에 남을 만한 것을 만들어 봅시다." },+ { id: "mr-IN", label: "Marathi", sample: "माझा आवाज असा आहे. चला काहीतरी संस्मरणीय बनवूया." },+ { id: "pl-PL", label: "Polish", sample: "Tak brzmi mój głos. Stwórzmy coś wartego zapamiętania." },+ { id: "pt-BR", label: "Portuguese", sample: "Esta é a minha voz. Vamos criar algo que valha a pena lembrar." },+ { id: "ro-RO", label: "Romanian", sample: "Așa sună vocea mea. Să creăm ceva demn de amintit." },+ { id: "ru-RU", label: "Russian", sample: "Вот как звучит мой голос. Давайте создадим что-то запоминающееся." },+ { id: "es-US", label: "Spanish", sample: "Así sueno. Hagamos algo digno de recordar." },+ { id: "ta-IN", label: "Tamil", sample: "என் குரல் இப்படித்தான் ஒலிக்கிறது. நினைவில் நிற்கும் ஒன்றை உருவாக்குவோம்." },+ { id: "te-IN", label: "Telugu", sample: "నా గొంతు ఇలా వినిపిస్తుంది. గుర్తుండిపోయేది ఒకటి చేద్దాం." },+ { id: "th-TH", label: "Thai", sample: "เสียงของฉันเป็นแบบนี้ มาสร้างสิ่งที่น่าจดจำกันเถอะ" },+ { id: "tr-TR", label: "Turkish", sample: "Sesim böyle. Hatırlanmaya değer bir şey yapalım." },+ { id: "uk-UA", label: "Ukrainian", sample: "Ось як звучить мій голос. Створімо щось варте пам'яті." },+ { id: "vi-VN", label: "Vietnamese", sample: "Giọng của tôi nghe như thế này. Hãy cùng tạo nên điều gì đó đáng nhớ." },+];++export const DEFAULT_LANGUAGE = "auto";++/** Resolve a requested speech language against the catalog: an exact+ * (case-insensitive) BCP-47 match, else a bare language ("es") to its catalog+ * variant, else auto-detect. Shared by every generation surface and the AI+ * copilot so a loose ask still lands on a supported code. */+export function resolveLanguage(wanted?: string): string {+ const w = wanted?.trim().toLowerCase();+ if (!w || w === "auto") return DEFAULT_LANGUAGE;+ const exact = SPEECH_LANGUAGES.find((l) => l.id.toLowerCase() === w);+ if (exact) return exact.id;+ const bare = SPEECH_LANGUAGES.find((l) => l.id.toLowerCase().startsWith(`${w}-`));+ return bare?.id ?? DEFAULT_LANGUAGE;+}+/** Resolve a requested voice against the catalog: an exact (or* case-insensitive) id match, else the default. Shared by the Audio panel and* the AI copilot so both land on the same voice. */@@ -117,9 +175,11 @@ async function readError(res: Response, fallback: string): Promise<string> {async function synthesizeSegment(text: string,voice: string,- direction?: string+ direction?: string,+ language?: string): Promise<PcmClip> {const style = direction?.trim();+ const languageCode = resolveLanguage(language);const res = await fetch("/api/inference/assets", {method: "POST",headers: { "Content-Type": "application/json", "x-donkey-client-id": CLIENT_ID },@@ -127,6 +187,9 @@ async function synthesizeSegment(kind: "speech",prompt: style ? `${style}: ${text}` : text,inputs: { voice },+ ...(languageCode !== DEFAULT_LANGUAGE+ ? { parameters: { languageCode } }+ : {}),}),});if (!res.ok) {@@ -213,7 +276,7 @@ export interface SpeechLayout {export async function synthesizeSpeech(projectId: string,segments: SpeechSegment[],- opts: { voice: string; direction?: string; name?: string }+ opts: { voice: string; direction?: string; language?: string; name?: string }): Promise<{ asset: MediaAsset; offset: number; layout: SpeechLayout[] }> {const lines = segments.map((s) => ({ text: s.text.trim(), at: Math.max(0, s.at) }))@@ -238,13 +301,13 @@ export async function synthesizeSpeech(const i = next++;try {try {- clips[i] = await synthesizeSegment(lines[i].text, voice, opts.direction);+ clips[i] = await synthesizeSegment(lines[i].text, voice, opts.direction, opts.language);} catch (e) {// An empty balance repeats forever — resending only burns the queue.if (e instanceof NoCreditsError) throw e;// The TTS backend rejects the odd call spuriously; one resend of just// this line usually lands and saves the rest of the batch.- clips[i] = await synthesizeSegment(lines[i].text, voice, opts.direction);+ clips[i] = await synthesizeSegment(lines[i].text, voice, opts.direction, opts.language);}} catch (e) {// Name the line that failed so a one-bad-cue batch is actionable.@@ -290,21 +353,20 @@ export async function synthesizeSpeech(return { asset, offset, layout };}-/** A short spoken sample for the voice picker. Each voice is synthesized once- * per session and cached as a blob URL. */+/** A short spoken sample for the voice picker, in the picked language. Each+ * voice+language pair is synthesized once per session and cached as a blob URL. */const samples = new Map<string, string>();-// Kept punchy but deliberately free of the "Hey!"-style lead that makes the TTS-// model intermittently return an empty clip (it stops before speaking). Change-// with care and re-check reliability across voices.-const SAMPLE_TEXT = "This is how I sound. Let's make something worth remembering.";-export async function speechSampleUrl(voice: string): Promise<string> {+export async function speechSampleUrl(voice: string, language?: string): Promise<string> {const id = resolveVoice(voice);- const cached = samples.get(id);+ const lang = resolveLanguage(language);+ const key = `${id}|${lang}`;+ const cached = samples.get(key);if (cached) return cached;- const clip = await synthesizeSegment(SAMPLE_TEXT, id);+ const text = SPEECH_LANGUAGES.find((l) => l.id === lang)?.sample ?? SAMPLE_TEXT;+ const clip = await synthesizeSegment(text, id, undefined, lang);const url = URL.createObjectURL(assembleWav([clip], [0]));- samples.set(id, url);+ samples.set(key, url);return url;}diff --git a/site/src/cut/lib/voiceover.ts b/site/src/cut/lib/voiceover.tsindex 42279f5b..ffda27e5 100644--- a/site/src/cut/lib/voiceover.ts+++ b/site/src/cut/lib/voiceover.ts@@ -15,7 +15,7 @@ export const DUCK_DEFAULT = 0.4;*/export async function generateSubtitlesReadout(voice: string,- opts?: { cueIds?: string[]; direction?: string; duck?: number }+ opts?: { cueIds?: string[]; direction?: string; language?: string; duck?: number }) {const s = useEditor.getState();const projectId = s.projectId;@@ -27,7 +27,7 @@ export async function generateSubtitlesReadout(const { asset, offset, layout } = await synthesizeSpeech(projectId,cues.map((c) => ({ text: c.text, at: c.start })),- { voice, direction: opts?.direction, name: "Subtitles readout" }+ { voice, direction: opts?.direction, language: opts?.language, name: "Subtitles readout" });const duck = opts?.duck ?? DUCK_DEFAULT;const cur = useEditor.getState();diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex c84b703a..bc5a6af2 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -224,6 +224,7 @@ export const AI_TOOLS: AiToolDef[] = [script: str("What the voice should say"),voice: str("Voice id from list_voices (optional; a sensible default is chosen)"),direction: str("Delivery instruction, e.g. 'Say warmly, like an old friend' (optional)"),+ language: str("Spoken language as BCP-47, e.g. es-US, ja-JP (optional; default auto-detects from the script — write the script in the target language)"),duck: num("Lower other audio to this gain while the voice plays, 0..1 (default 0.4; 1 = no ducking)"),start: num("Timeline start in seconds (default: the playhead)"),}, ["script"]),@@ -235,6 +236,7 @@ export const AI_TOOLS: AiToolDef[] = [inputSchema: obj({voice: str("Voice id from list_voices (optional)"),direction: str("Delivery instruction, e.g. 'Narrate briskly, documentary style' (optional)"),+ language: str("Spoken language as BCP-47, e.g. es-US, ja-JP (optional; default auto-detects — cues are spoken as written, so translate them first for another language)"),duck: num("Lower other audio to this gain while the voice plays, 0..1 (default 0.4)"),}),},@@ -395,7 +397,7 @@ Titles burn into the export exactly as previewed.`,Soundtrack clips: volume 0..1.5, fadeIn/fadeOut seconds (max half the clip), start = timeline position, in/out = trim inside the source. Fades render with ffmpeg afade on export.Ducking: a soundtrack clip's \`duck\` (0..1, via update_audio) lowers ALL other audio — video-clip sound and other music — to that gain while the clip plays; 1 clears it. Voiceovers set this so narration sits over quieter music. It applies in both the preview and the export.Voiceover (Donkey's hosted speech model — signed in, spends credits, like image/video generation):-- voiceover_generate(script, voice?, direction?, duck?, start?): synthesizes the script and drops it on the soundtrack at the playhead (or start). Defaults to a 0.4 duck so it sits over other audio. Voices are Gemini's prebuilt set — list_voices returns them (id + one-word character like Warm, Upbeat, Gravelly); omit voice for a good default. \`direction\` steers delivery in natural language ("Say warmly, like an old friend"); the script itself can carry inline tags like [whispers], [excited], [laughs].+- voiceover_generate(script, voice?, direction?, duck?, start?, language?): synthesizes the script and drops it on the soundtrack at the playhead (or start). Defaults to a 0.4 duck so it sits over other audio. Voices are Gemini's prebuilt set — list_voices returns them (id + one-word character like Warm, Upbeat, Gravelly); omit voice for a good default. \`direction\` steers delivery in natural language ("Say warmly, like an old friend"); the script itself can carry inline tags like [whispers], [excited], [laughs].- read_subtitles_aloud(voice?, direction?, duck?): speaks the existing subtitle cues, each line at its own cue time — captions become narration. Needs cues first.Subtitles: subtitles_generate transcribes the cut's audio on-device (Apple speech, macOS 26); cues are caption-sized (≈38 chars). subtitles_from_visuals is the fallback for a cut with NO speech — it watches sampled frames (via the user's Claude login) and writes timed narration captions of what's on screen. So: speech present → subtitles_generate; silent/music-only footage the user wants captioned → subtitles_from_visuals. Never fabricate a spoken transcript.captions_generate rewrites existing cues into punchy social captions (emoji, curiosity-hook opener) in a style (clean/hook/punchy), keeping timings — use it when the ask is social/TikTok captions rather than a plain transcript.