Spaces:
Running
Running
Update: ≤3s WeChat-compatible live photos, sets 3 & 4 (fill-in-the-blank), in-browser maker tool
0daf81d verified Download source/frontend/src/components/LiveMaker.tsx from Ethscriptions/eths: direct link, hf CLI and curl.
- Browser
- Download file 34.2 kB
-
https://huggingface.co/spaces/Ethscriptions/eths/resolve/main/source/frontend/src/components/LiveMaker.tsx
- Command line
-
hf download hf://spaces/Ethscriptions/eths/source/frontend/src/components/LiveMaker.tsx
-
curl -L -o LiveMaker.tsx https://huggingface.co/spaces/Ethscriptions/eths/resolve/main/source/frontend/src/components/LiveMaker.tsx
34.2 kB
| 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<CardSpec, 'image' | 'imgW' | 'imgH'> | |
| 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<HTMLImageElement> { | |
| 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<Photo> { | |
| 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 ( | |
| <section className="rounded-2xl border border-white/10 bg-white/[0.03] p-5"> | |
| <div className="mb-4 flex items-center justify-between gap-3"> | |
| <h3 className="flex items-center gap-2.5 text-base font-semibold"> | |
| <span className="inline-flex h-6 w-6 items-center justify-center rounded-full bg-white text-xs font-bold text-neutral-900">{step}</span> | |
| {title} | |
| </h3> | |
| {extra} | |
| </div> | |
| {children} | |
| </section> | |
| ) | |
| } | |
| function Field({ label, children, hint }: { label: string; children: ReactNode; hint?: string }) { | |
| return ( | |
| <label className="flex flex-col gap-1.5"> | |
| <span className="text-[13px] text-neutral-400">{label}</span> | |
| {children} | |
| {hint && <span className="text-xs text-neutral-500">{hint}</span>} | |
| </label> | |
| ) | |
| } | |
| 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 ( | |
| <label className="flex flex-col gap-1.5"> | |
| <span className="flex justify-between text-[13px] text-neutral-400"> | |
| {label} | |
| <span className="tabular-nums text-neutral-300">{fmt ? fmt(value) : value}</span> | |
| </span> | |
| <input type="range" min={min} max={max} step={step} value={value} onChange={(e) => onChange(Number(e.target.value))} className="accent-white" /> | |
| </label> | |
| ) | |
| } | |
| function Toggle({ label, checked, onChange }: { label: string; checked: boolean; onChange: (v: boolean) => void }) { | |
| return ( | |
| <button | |
| type="button" | |
| onClick={() => onChange(!checked)} | |
| className={`rounded-full border px-3.5 py-1.5 text-sm transition ${checked ? 'border-white bg-white text-neutral-900' : 'border-white/15 text-neutral-300 hover:border-white/40'}`} | |
| > | |
| {label} | |
| </button> | |
| ) | |
| } | |
| export default function LiveMaker() { | |
| const [fontsReady, setFontsReady] = useState(false) | |
| const [photo, setPhoto] = useState<Photo | null>(null) | |
| const [f, setF] = useState<Fields>(DEFAULT_FIELDS) | |
| const [voice, setVoice] = useState<Voice>({ clip: null, label: '' }) | |
| const [second, setSecond] = useState<'slow' | 'same' | 'none'>('slow') | |
| const [voiceVol, setVoiceVol] = useState(1) | |
| const [fx, setFx] = useState<SfxSettings>({ 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<Recording[] | null>(null) | |
| const [lookupMsg, setLookupMsg] = useState('') | |
| const [ttsVoice, setTtsVoice] = useState(TTS_VOICES[0][0]) | |
| const [recording, setRecording] = useState(false) | |
| const [results, setResults] = useState<ResultItem[]>([]) | |
| const [busy, setBusy] = useState<{ stage: string; ratio: number } | null>(null) | |
| const [error, setError] = useState('') | |
| const [playing, setPlaying] = useState(false) | |
| const canvasRef = useRef<HTMLCanvasElement>(null) | |
| const playRef = useRef<{ stop: () => void } | null>(null) | |
| const recRef = useRef<MediaRecorder | null>(null) | |
| const dragRef = useRef<{ x: number; y: number; cx: number; cy: number } | null>(null) | |
| const set = <K extends keyof Fields>(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<string, [Uint8Array, { level: 0 }]> = {} | |
| 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 ( | |
| <div className="grid gap-8 lg:grid-cols-[420px_minmax(0,1fr)]"> | |
| {/* preview column */} | |
| <div className="lg:sticky lg:top-6 lg:self-start"> | |
| <div className="relative mx-auto w-full max-w-[420px]"> | |
| <canvas | |
| ref={canvasRef} | |
| width={W} | |
| height={H} | |
| onPointerDown={onPointerDown} | |
| onPointerMove={onPointerMove} | |
| onPointerUp={onPointerUp} | |
| className="aspect-[3/4] w-full cursor-grab touch-none rounded-[22px] bg-neutral-900 ring-1 ring-white/10 active:cursor-grabbing" | |
| /> | |
| {!fontsReady && ( | |
| <div className="absolute inset-0 flex items-center justify-center text-sm text-neutral-400"> | |
| <Loader2 className="mr-2 h-4 w-4 animate-spin" /> 正在加载字体 | |
| </div> | |
| )} | |
| <span className="pointer-events-none absolute left-3 top-3 rounded-full bg-black/45 px-2.5 py-1 text-[11px] font-semibold text-white backdrop-blur"> | |
| LIVE · {dur.toFixed(1)}s | |
| </span> | |
| </div> | |
| <p className="mt-2 text-center text-xs text-neutral-500">拖动画面调整底图位置 · 上图为封面(静态图)</p> | |
| <div className="mt-4 flex gap-3"> | |
| <button type="button" onClick={play} disabled={!built || !!busy} className="inline-flex flex-1 items-center justify-center gap-2 rounded-full border border-white/20 py-3 font-medium hover:bg-white/10 disabled:opacity-40"> | |
| {playing ? <Pause className="h-4 w-4" /> : <Play className="h-4 w-4" />} | |
| {playing ? '停止' : '播放动画(有声)'} | |
| </button> | |
| <button type="button" onClick={generate} disabled={!built || !!busy || !photo} className="inline-flex flex-[1.3] items-center justify-center gap-2 rounded-full bg-white py-3 font-semibold text-neutral-900 hover:bg-neutral-200 disabled:opacity-40"> | |
| {busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Wand2 className="h-4 w-4" />} | |
| {busy ? `${busy.stage} ${Math.round(busy.ratio * 100)}%` : '生成实况图'} | |
| </button> | |
| </div> | |
| {busy && ( | |
| <div className="mt-3 h-1.5 overflow-hidden rounded-full bg-white/10"> | |
| <div className="h-full bg-white transition-all" style={{ width: `${Math.round(busy.ratio * 100)}%` }} /> | |
| </div> | |
| )} | |
| <label className="mt-4 flex cursor-pointer items-start gap-2.5 rounded-xl border border-white/10 px-3.5 py-3 text-sm"> | |
| <input type="checkbox" checked={f.compact} onChange={(e) => setF((p) => ({ ...p, compact: e.target.checked, hold: e.target.checked ? Math.min(p.hold, 0.6) : p.hold }))} className="mt-0.5 accent-white" /> | |
| <span> | |
| <span className="font-medium">微信朋友圈兼容(≤ 3 秒)</span> | |
| <span className="mt-0.5 block text-xs leading-5 text-neutral-500">朋友圈只接受 3 秒左右的实况,超长会提示「实况异常」。开启后自动压缩节奏,第二遍读音放不下时改为原速或只读一遍。</span> | |
| </span> | |
| </label> | |
| {built && f.compact && voice.clip && second !== 'none' && built.fitted !== second && ( | |
| <p className="mt-2 text-center text-xs text-amber-300/90"> | |
| {built.fitted === 'none' ? '3 秒内放不下第二遍读音,这张只读一遍' : '3 秒内放不下慢速第二遍,已改为原速'} | |
| </p> | |
| )} | |
| {built?.voiceCut && <p className="mt-2 text-center text-xs text-amber-300/90">读音太长,结尾会被截断,换一段更短的录音试试</p>} | |
| {!voice.clip && built && <p className="mt-3 text-center text-xs text-amber-300/90">还没有选读音,生成的实况只有音效</p>} | |
| {error && <p className="mt-3 text-center text-sm text-red-400">{error}</p>} | |
| <p className="mt-3 text-center text-xs leading-5 text-neutral-500"> | |
| 全部在你的浏览器里完成,图片和录音不会上传。首次生成需要下载约 32 MB 的视频编码器。 | |
| </p> | |
| {results.length > 0 && ( | |
| <div className="mt-6 rounded-2xl border border-white/10 p-4"> | |
| <div className="mb-3 flex items-center justify-between"> | |
| <span className="text-sm font-semibold">已生成 {results.length} 张</span> | |
| <button type="button" onClick={downloadAll} className="inline-flex items-center gap-1.5 rounded-full bg-white px-3.5 py-1.5 text-sm font-semibold text-neutral-900 hover:bg-neutral-200"> | |
| <Download className="h-4 w-4" /> 打包下载 ZIP | |
| </button> | |
| </div> | |
| <ul className="flex flex-col gap-3"> | |
| {results.map((r) => ( | |
| <li key={r.id} className="flex items-center gap-3"> | |
| <video src={r.videoURL} poster={r.coverURL} controls playsInline className="h-24 w-[72px] shrink-0 rounded-lg bg-black object-cover" /> | |
| <div className="min-w-0 flex-1"> | |
| <div className="truncate text-sm font-semibold">{r.en} · {r.zh}</div> | |
| <div className="text-xs text-neutral-500">{r.duration.toFixed(1)} 秒 · {r.name}</div> | |
| <div className="mt-2 flex gap-2"> | |
| <button type="button" onClick={() => download(r.jpg, `${r.name}.JPG`, 'image/jpeg')} className="rounded-md border border-white/15 px-2.5 py-1 text-xs hover:bg-white/10">JPG</button> | |
| <button type="button" onClick={() => download(r.mov, `${r.name}.MOV`, 'video/quicktime')} className="rounded-md border border-white/15 px-2.5 py-1 text-xs hover:bg-white/10">MOV</button> | |
| <button type="button" onClick={() => setResults((p) => p.filter((x) => x.id !== r.id))} className="ml-auto rounded-md px-2 py-1 text-neutral-500 hover:text-white" aria-label="删除"> | |
| <Trash2 className="h-3.5 w-3.5" /> | |
| </button> | |
| </div> | |
| </div> | |
| </li> | |
| ))} | |
| </ul> | |
| <p className="mt-3 text-xs leading-5 text-neutral-500">Mac 上把同名的 JPG 和 MOV 一起拖进「照片」App,就会识别成一张实况照片。</p> | |
| </div> | |
| )} | |
| </div> | |
| {/* settings column */} | |
| <div className="flex flex-col gap-5"> | |
| <Section step={1} title="底图"> | |
| <div className="flex flex-wrap gap-3"> | |
| <label className="inline-flex cursor-pointer items-center gap-2 rounded-full bg-white px-4 py-2 text-sm font-semibold text-neutral-900 hover:bg-neutral-200"> | |
| <ImagePlus className="h-4 w-4" /> 上传照片 | |
| <input | |
| type="file" | |
| accept="image/*" | |
| className="hidden" | |
| onChange={async (e) => { | |
| const file = e.target.files?.[0] | |
| if (!file) return | |
| try { | |
| const url = URL.createObjectURL(file) | |
| setPhoto(await toPhoto(url, file.name)) | |
| set('crop', { zoom: 1, x: 0.5, y: 0.5 }) | |
| } catch { | |
| setError('这张图片无法读取,换成 JPG / PNG 试试') | |
| } | |
| e.target.value = '' | |
| }} | |
| /> | |
| </label> | |
| <span className="self-center text-xs text-neutral-500">建议竖拍照片,会自动裁成 3:4(1080×1440)</span> | |
| </div> | |
| <div className="mt-4"> | |
| <div className="mb-2 text-[13px] text-neutral-400">或者用示例图片</div> | |
| <div className="grid grid-cols-6 gap-2"> | |
| {SAMPLES.map((s) => ( | |
| <button key={s.key} type="button" onClick={() => pickSample(s)} title={`${s.zh} · ${s.note}`} className={`overflow-hidden rounded-lg ring-2 transition ${photo?.name === s.key ? 'ring-white' : 'ring-transparent hover:ring-white/40'}`}> | |
| <img src={`${base}samples/${s.key}.jpg`} alt={s.zh} className="aspect-[3/4] w-full object-cover" loading="lazy" /> | |
| </button> | |
| ))} | |
| </div> | |
| <p className="mt-2 text-[11px] text-neutral-500">示例中红绿灯、包子、打哈欠来自 Wikimedia Commons(作者见鼠标悬停提示),其余为 AI 生成。</p> | |
| </div> | |
| <div className="mt-4 grid gap-4 sm:grid-cols-2"> | |
| <Range label="放大" value={f.crop.zoom} min={1} max={2.5} step={0.01} onChange={(v) => set('crop', { ...f.crop, zoom: v })} fmt={(v) => `${v.toFixed(2)}×`} /> | |
| <Range label="卡片位置(上 ↔ 下)" value={f.cardY} min={0.2} max={0.8} step={0.01} onChange={(v) => set('cardY', v)} fmt={(v) => `${Math.round(v * 100)}%`} /> | |
| </div> | |
| </Section> | |
| <Section step={2} title="单词"> | |
| <div className="grid gap-4 sm:grid-cols-2"> | |
| <Field label="英文"> | |
| <div className="flex gap-2"> | |
| <input | |
| className={`${inputCls} min-w-0 flex-1`} | |
| value={f.en} | |
| onChange={(e) => { | |
| set('en', e.target.value) | |
| setVoice({ clip: null, label: '' }) | |
| setRecs(null) | |
| }} | |
| onBlur={() => recs === null && runLookup(f.en, false)} | |
| placeholder="umbrella" | |
| /> | |
| <button type="button" onClick={() => runLookup(f.en, true)} className="inline-flex h-10 items-center gap-1.5 rounded-lg border border-white/15 px-3 text-sm hover:bg-white/10"> | |
| <Search className="h-4 w-4" /> 查询 | |
| </button> | |
| </div> | |
| </Field> | |
| <Field label="中文"> | |
| <input className={inputCls} value={f.zh} onChange={(e) => set('zh', e.target.value)} placeholder="雨伞" /> | |
| </Field> | |
| <Field label="音标" hint="点「查询」会从维基词典自动填入,可手动修改"> | |
| <input className={inputCls} value={f.ipa} onChange={(e) => set('ipa', e.target.value)} placeholder="/ʌmˈbrelə/" /> | |
| </Field> | |
| <Field label="词性"> | |
| <select className={inputCls} value={f.pos} onChange={(e) => set('pos', e.target.value)}> | |
| {['n.', 'v.', 'adj.', 'adv.', 'phr.', 'prep.', 'int.', ''].map((p) => ( | |
| <option key={p} value={p}>{p || '不显示'}</option> | |
| ))} | |
| </select> | |
| </Field> | |
| </div> | |
| </Section> | |
| <Section step={3} title="读音" extra={voice.clip ? <span className="inline-flex items-center gap-1 text-xs text-emerald-400"><Volume2 className="h-3.5 w-3.5" />{voice.label} · {(voice.clip.length / SR).toFixed(1)}s</span> : null}> | |
| <div className="mb-4 flex flex-wrap gap-2"> | |
| {([['commons', '真人录音'], ['upload', '上传音频'], ['record', '自己录'], ['tts', '语音合成']] as const).map(([k, l]) => ( | |
| <Toggle key={k} label={l} checked={voiceTab === k} onChange={() => { | |
| setVoiceTab(k) | |
| if (k === 'commons' && recs === null) runLookup(f.en, false) | |
| }} /> | |
| ))} | |
| </div> | |
| {voiceTab === 'commons' && ( | |
| <div> | |
| <p className="mb-3 text-xs text-neutral-500">来自维基共享资源(Wikimedia Commons)志愿者录制的真人发音,多为 CC BY-SA 授权。</p> | |
| {recs === null && ( | |
| <button type="button" onClick={() => runLookup(f.en, false)} className="inline-flex items-center gap-1.5 rounded-lg border border-white/15 px-3 py-2 text-sm hover:bg-white/10"> | |
| <Search className="h-4 w-4" /> 查找「{f.en}」的真人录音 | |
| </button> | |
| )} | |
| {recs && recs.length > 0 && ( | |
| <ul className="flex flex-col gap-2"> | |
| {recs.map((r) => ( | |
| <li key={r.title} className="flex items-center gap-2 rounded-lg border border-white/10 px-3 py-2"> | |
| <button type="button" onClick={() => new Audio(r.url).play().catch(() => undefined)} className="rounded-full p-1.5 hover:bg-white/10" aria-label="试听"> | |
| <Play className="h-4 w-4" /> | |
| </button> | |
| <a href={r.page} target="_blank" rel="noopener noreferrer" className="min-w-0 flex-1 truncate text-sm text-neutral-200 hover:underline">{r.label}</a> | |
| <button type="button" onClick={() => applyRecording(r)} className="rounded-md bg-white px-3 py-1 text-xs font-semibold text-neutral-900 hover:bg-neutral-200">使用</button> | |
| </li> | |
| ))} | |
| </ul> | |
| )} | |
| </div> | |
| )} | |
| {voiceTab === 'upload' && ( | |
| <label className="inline-flex cursor-pointer items-center gap-2 rounded-lg border border-white/15 px-3 py-2 text-sm hover:bg-white/10"> | |
| <Upload className="h-4 w-4" /> 选择音频文件(mp3 / m4a / wav) | |
| <input type="file" accept="audio/*" className="hidden" onChange={(e) => e.target.files?.[0] && onAudioFile(e.target.files[0])} /> | |
| </label> | |
| )} | |
| {voiceTab === 'record' && ( | |
| <div className="flex items-center gap-3"> | |
| <button type="button" onClick={toggleRecord} className={`inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-semibold ${recording ? 'bg-red-500 text-white' : 'bg-white text-neutral-900 hover:bg-neutral-200'}`}> | |
| {recording ? <Square className="h-4 w-4" /> : <Mic className="h-4 w-4" />} | |
| {recording ? '停止录音' : '开始录音'} | |
| </button> | |
| <span className="text-xs text-neutral-500">读一遍单词即可,最长 6 秒,首尾静音会自动剪掉</span> | |
| </div> | |
| )} | |
| {voiceTab === 'tts' && ( | |
| <div className="flex flex-wrap items-center gap-3"> | |
| <select className={inputCls} value={ttsVoice} onChange={(e) => setTtsVoice(e.target.value)}> | |
| {TTS_VOICES.map(([v, l]) => <option key={v} value={v}>{l}</option>)} | |
| </select> | |
| <button type="button" onClick={runTTS} className="rounded-lg bg-white px-4 py-2 text-sm font-semibold text-neutral-900 hover:bg-neutral-200">合成「{f.en}」</button> | |
| <span className="w-full text-xs text-neutral-500">找不到真人录音时的备选,使用神经网络语音(属于 AI),需要网站后端。</span> | |
| </div> | |
| )} | |
| {lookupMsg && <p className="mt-3 text-xs text-neutral-400">{lookupMsg}</p>} | |
| <div className="mt-5 grid gap-4 sm:grid-cols-2"> | |
| <Field label="第二遍"> | |
| <select className={inputCls} value={second} onChange={(e) => setSecond(e.target.value as typeof second)}> | |
| <option value="slow">放慢再读一遍</option> | |
| <option value="same">原速再读一遍</option> | |
| <option value="none">只读一遍</option> | |
| </select> | |
| </Field> | |
| <Range label="人声音量" value={voiceVol} min={0} max={1.5} step={0.05} onChange={setVoiceVol} fmt={(v) => `${Math.round(v * 100)}%`} /> | |
| </div> | |
| </Section> | |
| <Section step={4} title="音效"> | |
| <div className="flex flex-wrap gap-2"> | |
| <Toggle label="揭晓转场" checked={fx.whoosh} onChange={(v) => setFx({ ...fx, whoosh: v })} /> | |
| <Toggle label="打字叮叮" checked={fx.tick} onChange={(v) => setFx({ ...fx, tick: v })} /> | |
| <Toggle label="完成提示音" checked={fx.chime} onChange={(v) => setFx({ ...fx, chime: v })} /> | |
| <Toggle label="闪光尾音" checked={fx.shimmer} onChange={(v) => setFx({ ...fx, shimmer: v })} /> | |
| <Toggle label="弹出音" checked={fx.pop} onChange={(v) => setFx({ ...fx, pop: v })} /> | |
| </div> | |
| <div className="mt-4 max-w-sm"> | |
| <Range label="音效音量" value={fx.volume} min={0} max={1.5} step={0.05} onChange={(v) => setFx({ ...fx, volume: v })} fmt={(v) => `${Math.round(v * 100)}%`} /> | |
| </div> | |
| </Section> | |
| <Section step={5} title="样式"> | |
| <div className="grid grid-cols-5 gap-2"> | |
| {STYLES.map((s) => ( | |
| <button key={s.id} type="button" onClick={() => set('styleId', s.id)} className={`flex flex-col items-center gap-2 rounded-xl border p-2.5 text-xs transition ${f.styleId === s.id ? 'border-white bg-white/10' : 'border-white/10 hover:border-white/30'}`}> | |
| <span className="h-9 w-full rounded-md ring-1 ring-white/10" style={{ background: s.swatch }} /> | |
| {s.name} | |
| </button> | |
| ))} | |
| </div> | |
| <div className="mt-5"> | |
| <div className="mb-2 text-[13px] text-neutral-400">强调色(关键词、喇叭图标)</div> | |
| <div className="flex flex-wrap items-center gap-2"> | |
| {ACCENTS.map((c) => ( | |
| <button key={c} type="button" onClick={() => set('accent', c)} aria-label={c} className={`h-8 w-8 rounded-full ring-2 ring-offset-2 ring-offset-[#0d0d10] ${f.accent === c ? 'ring-white' : 'ring-transparent'}`} style={{ background: c }} /> | |
| ))} | |
| <input type="color" value={f.accent} onChange={(e) => set('accent', e.target.value)} className="h-8 w-10 cursor-pointer rounded border-0 bg-transparent" /> | |
| </div> | |
| </div> | |
| <div className="mt-5 grid gap-4 sm:grid-cols-2"> | |
| <Field label="提问文案" hint="{zh} 会替换成中文并高亮"> | |
| <input className={inputCls} value={f.question} onChange={(e) => set('question', e.target.value)} /> | |
| </Field> | |
| <div className="grid grid-cols-2 gap-3"> | |
| <Field label="提问标签"> | |
| <input className={inputCls} value={f.pillQ} onChange={(e) => set('pillQ', e.target.value)} disabled={!f.showPill} /> | |
| </Field> | |
| <Field label="揭晓标签"> | |
| <input className={inputCls} value={f.pillA} onChange={(e) => set('pillA', e.target.value)} disabled={!f.showPill} /> | |
| </Field> | |
| </div> | |
| </div> | |
| <div className="mt-5 flex flex-wrap gap-2"> | |
| <Toggle label="显示标签" checked={f.showPill} onChange={(v) => set('showPill', v)} /> | |
| <Toggle label="镜头微动" checked={f.motion} onChange={(v) => set('motion', v)} /> | |
| <Toggle label="胶片颗粒" checked={f.grain} onChange={(v) => set('grain', v)} /> | |
| <Toggle label="彩纸" checked={f.confetti} onChange={(v) => set('confetti', v)} /> | |
| <Toggle label="扫光" checked={f.sweep} onChange={(v) => set('sweep', v)} /> | |
| </div> | |
| <div className="mt-5 max-w-sm"> | |
| <Range label="揭晓前停留" value={f.hold} min={0.25} max={f.compact ? 0.6 : 1.5} step={0.05} onChange={(v) => set('hold', v)} fmt={(v) => `${v.toFixed(2)} 秒`} /> | |
| </div> | |
| </Section> | |
| </div> | |
| </div> | |
| ) | |
| } | |