import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react' import { zipSync } from 'fflate' import { Download, ImagePlus, Loader2, Mic, Pause, Play, Search, Square, Trash2, Upload, Volume2, Wand2 } from 'lucide-react' import { api } from '@/lib/api' import { cleanVoice, decodeToMono, SR } from '@/lib/live/audio' import { encodeLive, type LiveResult } from '@/lib/live/encode' import { loadFonts } from '@/lib/live/fonts' import { fetchAudio, findRecordings, lookupWord, type Recording } from '@/lib/live/lookup' import { build, type SfxSettings } from '@/lib/live/project' import { FPS, H, W, type CardSpec } from '@/lib/live/renderer' import { STYLES } from '@/lib/live/styles' type Fields = Omit interface Photo { src: HTMLCanvasElement w: number h: number name: string } interface Voice { clip: Float32Array | null label: string } interface ResultItem extends LiveResult { name: string en: string zh: string } const base = import.meta.env.BASE_URL const SAMPLES = [ { key: 'slippers', en: 'slippers', zh: '拖鞋', ipa: '/ˈslɪpərz/', pos: 'n.', note: 'AI 生成' }, { key: 'umbrella', en: 'umbrella', zh: '雨伞', ipa: '/ʌmˈbrelə/', pos: 'n.', note: 'AI 生成' }, { key: 'bubble-tea', en: 'bubble tea', zh: '奶茶', ipa: '/ˈbʌbəl tiː/', pos: 'n.', note: 'AI 生成' }, { key: 'traffic-light', en: 'traffic light', zh: '红绿灯', ipa: '/ˈtræfɪk laɪt/', pos: 'n.', note: 'Gary · CC BY-SA 2.0' }, { key: 'steamed-bun', en: 'steamed bun', zh: '包子', ipa: '/ˌstiːmd ˈbʌn/', pos: 'n.', note: 'Guilhem Vellut · CC BY 2.0' }, { key: 'yawn', en: 'yawn', zh: '打哈欠', ipa: '/jɔːn/', pos: 'v.', note: 'Wheeler Cowperthwaite · CC BY 2.0' }, ] const ACCENTS = ['#ff3b5c', '#ff7a1a', '#f5b700', '#16a34a', '#2563eb', '#7c3aed', '#111114'] const TTS_VOICES = [ ['en-US-AvaMultilingualNeural', '美式女声'], ['en-US-AndrewMultilingualNeural', '美式男声'], ['en-GB-SoniaNeural', '英式女声'], ['en-GB-RyanNeural', '英式男声'], ] const DEFAULT_FIELDS: Fields = { crop: { zoom: 1, x: 0.5, y: 0.5 }, en: 'slippers', zh: '拖鞋', ipa: '/ˈslɪpərz/', pos: 'n.', question: '「{zh}」用英语怎么说?', pillQ: '在线求助', pillA: '答案揭晓', showPill: true, styleId: 'glass', accent: '#ff3b5c', cardY: 0.5, motion: true, grain: true, confetti: true, sweep: true, hold: 0.35, compact: true, } function loadImage(url: string): Promise { return new Promise((res, rej) => { const im = new Image() im.crossOrigin = 'anonymous' im.onload = () => res(im) im.onerror = () => rej(new Error('图片无法读取')) im.src = url }) } async function toPhoto(url: string, name: string): Promise { const im = await loadImage(url) const s = Math.min(1, 2400 / Math.max(im.naturalWidth, im.naturalHeight)) const c = document.createElement('canvas') c.width = Math.round(im.naturalWidth * s) c.height = Math.round(im.naturalHeight * s) const x = c.getContext('2d')! x.imageSmoothingQuality = 'high' x.drawImage(im, 0, 0, c.width, c.height) return { src: c, w: c.width, h: c.height, name } } const slug = (s: string) => s.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'word' function download(data: Uint8Array | Blob, name: string, type = 'application/octet-stream') { const blob = data instanceof Blob ? data : new Blob([data as BlobPart], { type }) const a = document.createElement('a') a.href = URL.createObjectURL(blob) a.download = name document.body.appendChild(a) a.click() a.remove() setTimeout(() => URL.revokeObjectURL(a.href), 5000) } function Section({ step, title, children, extra }: { step: number; title: string; children: ReactNode; extra?: ReactNode }) { return (

{step} {title}

{extra}
{children}
) } function Field({ label, children, hint }: { label: string; children: ReactNode; hint?: string }) { return ( ) } const inputCls = 'h-10 rounded-lg border border-white/10 bg-black/30 px-3 text-[15px] text-white outline-none focus:border-white/40' function Range({ label, value, min, max, step, onChange, fmt }: { label: string; value: number; min: number; max: number; step: number; onChange: (v: number) => void; fmt?: (v: number) => string }) { return ( ) } function Toggle({ label, checked, onChange }: { label: string; checked: boolean; onChange: (v: boolean) => void }) { return ( ) } export default function LiveMaker() { const [fontsReady, setFontsReady] = useState(false) const [photo, setPhoto] = useState(null) const [f, setF] = useState(DEFAULT_FIELDS) const [voice, setVoice] = useState({ clip: null, label: '' }) const [second, setSecond] = useState<'slow' | 'same' | 'none'>('slow') const [voiceVol, setVoiceVol] = useState(1) const [fx, setFx] = useState({ whoosh: true, tick: true, chime: true, shimmer: true, pop: true, volume: 1 }) const [voiceTab, setVoiceTab] = useState<'commons' | 'upload' | 'record' | 'tts'>('commons') const [recs, setRecs] = useState(null) const [lookupMsg, setLookupMsg] = useState('') const [ttsVoice, setTtsVoice] = useState(TTS_VOICES[0][0]) const [recording, setRecording] = useState(false) const [results, setResults] = useState([]) const [busy, setBusy] = useState<{ stage: string; ratio: number } | null>(null) const [error, setError] = useState('') const [playing, setPlaying] = useState(false) const canvasRef = useRef(null) const playRef = useRef<{ stop: () => void } | null>(null) const recRef = useRef(null) const dragRef = useRef<{ x: number; y: number; cx: number; cy: number } | null>(null) const set = (k: K, v: Fields[K]) => setF((p) => ({ ...p, [k]: v })) useEffect(() => { loadFonts().then(() => setFontsReady(true)).catch(() => setFontsReady(true)) toPhoto(`${base}samples/slippers.jpg`, 'slippers').then(setPhoto).catch(() => undefined) }, []) const spec: CardSpec = useMemo(() => ({ ...f, image: photo?.src ?? null, imgW: photo?.w ?? 0, imgH: photo?.h ?? 0 }), [f, photo]) const built = useMemo(() => (fontsReady && spec.en.trim() ? build(spec, { clip: voice.clip, second, volume: voiceVol }, fx) : null), [fontsReady, spec, voice, second, voiceVol, fx]) // draw the cover frame whenever settings change useEffect(() => { if (!built || playing) return const ctx = canvasRef.current?.getContext('2d') if (ctx) built.renderer.frame(ctx, built.T.coverFrame) }, [built, playing]) // ----- word lookup ----- const runLookup = useCallback(async (word: string, fillText: boolean) => { if (!word.trim()) return setLookupMsg('正在查询音标和真人发音…') setRecs(null) const [info, rec] = await Promise.allSettled([lookupWord(word), findRecordings(word)]) let note = '' if (fillText) { if (info.status === 'fulfilled') { setF((p) => ({ ...p, ipa: info.value.ipa || p.ipa, pos: info.value.pos || p.pos })) if (!info.value.ipa) note = '维基词典里没有这个词的音标,请手动填写。' } else note = '音标查询失败,请手动填写。' } if (rec.status === 'fulfilled') { setRecs(rec.value) setLookupMsg(note + (rec.value.length ? '' : '维基共享资源里没有找到这个词的真人录音,可以上传、录音或用语音合成。')) } else { setRecs([]) setLookupMsg(note + '录音查询失败,请稍后再试,或改用上传 / 录音。') } }, []) const applyRecording = async (r: Recording) => { try { setLookupMsg(`正在载入 ${r.label}…`) const clip = cleanVoice(await decodeToMono(await fetchAudio(r.url))) setVoice({ clip, label: `${r.label}(维基共享资源真人录音)` }) setLookupMsg('') } catch { setLookupMsg('这段录音无法载入,换一条试试') } } const onAudioFile = async (file: File) => { try { const clip = cleanVoice(await decodeToMono(await file.arrayBuffer())) setVoice({ clip, label: `上传:${file.name}` }) } catch { setError('这个音频格式无法识别,试试 mp3 / m4a / wav') } } const toggleRecord = async () => { if (recording) { recRef.current?.stop() return } try { const stream = await navigator.mediaDevices.getUserMedia({ audio: true }) const mr = new MediaRecorder(stream) const parts: Blob[] = [] mr.ondataavailable = (e) => parts.push(e.data) mr.onstop = async () => { stream.getTracks().forEach((t) => t.stop()) setRecording(false) try { const clip = cleanVoice(await decodeToMono(await new Blob(parts).arrayBuffer())) setVoice({ clip, label: '我的录音' }) } catch { setError('录音解析失败,请重试') } } recRef.current = mr mr.start() setRecording(true) setTimeout(() => mr.state === 'recording' && mr.stop(), 6000) } catch { setError('无法使用麦克风,请在浏览器里允许麦克风权限') } } const runTTS = async () => { try { setLookupMsg('正在合成…') const r = await fetch(api(`tts?text=${encodeURIComponent(f.en)}&voice=${ttsVoice}&rate=-5`)) if (!r.ok) throw new Error() const clip = cleanVoice(await decodeToMono(await r.arrayBuffer())) setVoice({ clip, label: `语音合成:${TTS_VOICES.find((v) => v[0] === ttsVoice)?.[1]}` }) setLookupMsg('') } catch { setLookupMsg('语音合成暂不可用(静态部署时没有后端),请改用真人录音、上传或录音') } } // ----- preview playback ----- const stopPlay = () => { playRef.current?.stop() playRef.current = null setPlaying(false) } const play = () => { if (!built) return if (playing) return stopPlay() const actx = new AudioContext() const src = actx.createBufferSource() src.buffer = built.mixer.toAudioBuffer(actx) src.connect(actx.destination) const ctx = canvasRef.current!.getContext('2d')! let raf = 0 let alive = true const t0 = actx.currentTime + 0.05 src.start(t0) const loop = () => { if (!alive) return const t = actx.currentTime - t0 const fi = Math.max(0, Math.floor(t * FPS)) if (fi >= built.T.nf) { stopPlay() return } built.renderer.frame(ctx, fi) raf = requestAnimationFrame(loop) } raf = requestAnimationFrame(loop) playRef.current = { stop: () => { alive = false cancelAnimationFrame(raf) try { src.stop() } catch { /* already stopped */ } actx.close() }, } setPlaying(true) } useEffect(() => () => playRef.current?.stop(), []) // ----- drag to reposition the photo ----- const onPointerDown = (e: React.PointerEvent) => { if (!photo) return ;(e.target as HTMLElement).setPointerCapture(e.pointerId) dragRef.current = { x: e.clientX, y: e.clientY, cx: f.crop.x, cy: f.crop.y } } const onPointerMove = (e: React.PointerEvent) => { const d = dragRef.current if (!d || !photo) return const rect = (e.target as HTMLElement).getBoundingClientRect() const bw = Math.min(photo.w, (photo.h * 3) / 4) / f.crop.zoom const k = bw / rect.width set('crop', { ...f.crop, x: d.cx - ((e.clientX - d.x) * k) / photo.w, y: d.cy - ((e.clientY - d.y) * k) / photo.h }) } const onPointerUp = () => { dragRef.current = null if (!photo) return // clamp so the 3:4 window stays inside the photo const bw = Math.min(photo.w, (photo.h * 3) / 4) / f.crop.zoom const bh = (bw * 4) / 3 const cx = Math.min(1 - bw / 2 / photo.w, Math.max(bw / 2 / photo.w, f.crop.x)) const cy = Math.min(1 - bh / 2 / photo.h, Math.max(bh / 2 / photo.h, f.crop.y)) set('crop', { ...f.crop, x: cx, y: cy }) } // ----- generate ----- const generate = async () => { if (!built) return stopPlay() setError('') setBusy({ stage: '准备', ratio: 0 }) try { const res = await encodeLive(built.renderer, built.mixer.wav(), (stage, ratio) => setBusy({ stage, ratio })) const baseName = `LIVE_${slug(f.en)}` const used = results.filter((r) => r.name === baseName || r.name.startsWith(baseName + '_')).length setResults((p) => [{ ...res, name: used ? `${baseName}_${used + 1}` : baseName, en: f.en, zh: f.zh }, ...p]) } catch (e) { setError(`生成失败:${e instanceof Error ? e.message : String(e)}`) } finally { setBusy(null) const ctx = canvasRef.current?.getContext('2d') if (ctx && built) built.renderer.frame(ctx, built.T.coverFrame) } } const downloadAll = () => { const files: Record = {} for (const r of results) { files[`${r.name}.JPG`] = [r.jpg, { level: 0 }] files[`${r.name}.MOV`] = [r.mov, { level: 0 }] } download(zipSync(files), `live-photos-${results.length}.zip`, 'application/zip') } const pickSample = async (s: (typeof SAMPLES)[number]) => { setPhoto(await toPhoto(`${base}samples/${s.key}.jpg`, s.key)) setF((p) => ({ ...p, en: s.en, zh: s.zh, ipa: s.ipa, pos: s.pos, crop: { zoom: 1, x: 0.5, y: 0.5 } })) setVoice({ clip: null, label: '' }) setRecs(null) } const dur = built ? built.T.dur : 0 return (
{/* preview column */}
{!fontsReady && (
正在加载字体
)} LIVE · {dur.toFixed(1)}s

拖动画面调整底图位置 · 上图为封面(静态图)

{busy && (
)} {built && f.compact && voice.clip && second !== 'none' && built.fitted !== second && (

{built.fitted === 'none' ? '3 秒内放不下第二遍读音,这张只读一遍' : '3 秒内放不下慢速第二遍,已改为原速'}

)} {built?.voiceCut &&

读音太长,结尾会被截断,换一段更短的录音试试

} {!voice.clip && built &&

还没有选读音,生成的实况只有音效

} {error &&

{error}

}

全部在你的浏览器里完成,图片和录音不会上传。首次生成需要下载约 32 MB 的视频编码器。

{results.length > 0 && (
已生成 {results.length} 张
    {results.map((r) => (
  • ))}

Mac 上把同名的 JPG 和 MOV 一起拖进「照片」App,就会识别成一张实况照片。

)}
{/* settings column */}
建议竖拍照片,会自动裁成 3:4(1080×1440)
或者用示例图片
{SAMPLES.map((s) => ( ))}

示例中红绿灯、包子、打哈欠来自 Wikimedia Commons(作者见鼠标悬停提示),其余为 AI 生成。

set('crop', { ...f.crop, zoom: v })} fmt={(v) => `${v.toFixed(2)}×`} /> set('cardY', v)} fmt={(v) => `${Math.round(v * 100)}%`} />
{ set('en', e.target.value) setVoice({ clip: null, label: '' }) setRecs(null) }} onBlur={() => recs === null && runLookup(f.en, false)} placeholder="umbrella" />
set('zh', e.target.value)} placeholder="雨伞" /> set('ipa', e.target.value)} placeholder="/ʌmˈbrelə/" />
{voice.label} · {(voice.clip.length / SR).toFixed(1)}s : null}>
{([['commons', '真人录音'], ['upload', '上传音频'], ['record', '自己录'], ['tts', '语音合成']] as const).map(([k, l]) => ( { setVoiceTab(k) if (k === 'commons' && recs === null) runLookup(f.en, false) }} /> ))}
{voiceTab === 'commons' && (

来自维基共享资源(Wikimedia Commons)志愿者录制的真人发音,多为 CC BY-SA 授权。

{recs === null && ( )} {recs && recs.length > 0 && (
    {recs.map((r) => (
  • {r.label}
  • ))}
)}
)} {voiceTab === 'upload' && ( )} {voiceTab === 'record' && (
读一遍单词即可,最长 6 秒,首尾静音会自动剪掉
)} {voiceTab === 'tts' && (
找不到真人录音时的备选,使用神经网络语音(属于 AI),需要网站后端。
)} {lookupMsg &&

{lookupMsg}

}
`${Math.round(v * 100)}%`} />
setFx({ ...fx, whoosh: v })} /> setFx({ ...fx, tick: v })} /> setFx({ ...fx, chime: v })} /> setFx({ ...fx, shimmer: v })} /> setFx({ ...fx, pop: v })} />
setFx({ ...fx, volume: v })} fmt={(v) => `${Math.round(v * 100)}%`} />
{STYLES.map((s) => ( ))}
强调色(关键词、喇叭图标)
{ACCENTS.map((c) => (
set('question', e.target.value)} />
set('pillQ', e.target.value)} disabled={!f.showPill} /> set('pillA', e.target.value)} disabled={!f.showPill} />
set('showPill', v)} /> set('motion', v)} /> set('grain', v)} /> set('confetti', v)} /> set('sweep', v)} />
set('hold', v)} fmt={(v) => `${v.toFixed(2)} 秒`} />
) }