import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { zipSync } from 'fflate' import './styles.css' import { DURATION } from './engine/audio' import { Renderer } from './engine/renderer' import { SCENES, sceneAt } from './engine/timeline' import { AUDIO_URL, ensureLyricFont, loadFonts } from './fonts' import { exportMp4, exportRenderer, webCodecsSupported, type ExportResult } from './export/exportMp4' import { DESIGNS, RATIOS, RATIO_SIZE, renderCover, type CoverItem, type Ratio } from './covers/covers' import { PLATFORMS, countChars, formatTags } from './copy/platforms' import { getLyricOffset, loadSavedLyrics, lyricCount, parseLrc, setLyricOffset, setLyrics } from './engine/lyrics' import { bus } from './playerBus' type Orient = 'landscape' | 'portrait' const fmt = (t: number) => { const m = Math.floor(t / 60) const s = Math.floor(t % 60) return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}` } function useToast() { const [msg, setMsg] = useState(null) const timer = useRef(0) const show = useCallback((m: string) => { setMsg(m) window.clearTimeout(timer.current) timer.current = window.setTimeout(() => setMsg(null), 1600) }, []) return { msg, show } } async function copyText(text: string): Promise { try { await navigator.clipboard.writeText(text) return true } catch { const ta = document.createElement('textarea') ta.value = text ta.style.position = 'fixed' ta.style.opacity = '0' document.body.appendChild(ta) ta.select() let ok = false try { ok = document.execCommand('copy') } catch { ok = false } document.body.removeChild(ta) return ok } } function download(url: string, name: string) { const a = document.createElement('a') a.href = url a.download = name document.body.appendChild(a) a.click() a.remove() } // ====================================================================== App export default function MvApp() { const [ready, setReady] = useState(false) // landscape 16:9 only (portrait was dropped on request) const orient: Orient = 'landscape' const setOrient = (_o: Orient) => {} const toast = useToast() useEffect(() => { loadFonts().then(() => setReady(true)) // debug / QA hook: render a single frame offscreen ;(window as unknown as { __mvSnap: unknown }).__mvSnap = async (t: number, w: number, h: number) => { await loadFonts() const r = exportRenderer() r.setSize(w, h) const t0 = performance.now() r.render(t) const ms = performance.now() - t0 return { url: r.out.toDataURL('image/jpeg', 0.85), ms, webgl: r.webgl } } ;(window as unknown as { __mvExport: unknown }).__mvExport = exportMp4 ;(window as unknown as { __mvSetLyrics: unknown }).__mvSetLyrics = async (src: string) => { const n = setLyrics(src, false) await ensureLyricFont() return n } ;(window as unknown as { __mvSheet: unknown }).__mvSheet = async (which: string, w: number, h: number) => { const H = await import('./engine/hero') const c = document.createElement('canvas') c.width = w c.height = h const g = c.getContext('2d')! g.fillStyle = '#8a96a6' g.fillRect(0, 0, w, h) const s = Math.min(w, h) if (which === 'walk') H.heroWalk(g, w / 2, h * 0.95, h * 0.9, 0.2, { t: 1 }) if (which === 'back') H.heroBack(g, w / 2, h * 0.95, h * 0.9, 0, { t: 1 }) if (which === 'bike') H.bike(g, w / 2, h * 0.85, s * 0.62, { t: 1, parked: true }) if (which === 'ride') H.heroRide(g, w / 2, h * 0.95, s * 0.6, { t: 1, smile: true, tuck: 0 }) if (which === 'rear') H.heroRideRear(g, w / 2, h * 0.98, h * 0.9, 0, 1) if (which === 'sit') { H.bike(g, w * 0.62, h * 0.95, (h * 0.75) / H.HERO_H, { facing: -1, light: 0, parked: true }) H.heroSit(g, w * 0.36, h * 0.95, h * 0.75, 1, { fire: 0 }) } if (which === 'push') H.heroPush(g, w * 0.5, h * 0.95, (h * 0.85) / H.HERO_H, 0.2, { t: 1, light: 1 }) if (which === 'face') H.heroPortrait(g, w / 2, h * 0.42, h * 0.22, { t: 1, tear: 0.5 }) return c.toDataURL('image/png') } }, []) return (
黑街
BLACK STREET · MV
陈雅雯《黑街》 · 浏览器实时渲染
画面为原创程序化动画(Canvas 2D + WebGL),所有渲染、导出都在你的浏览器本地完成,不上传任何数据。
音乐《黑街》原唱陈雅雯,DJ 版 DJ鐘董,版权归原作者所有。
{toast.msg &&
{toast.msg}
}
) } // ====================================================================== Player function Player({ ready, orient, setOrient }: { ready: boolean; orient: Orient; setOrient: (o: Orient) => void }) { const canvasRef = useRef(null) const audioRef = useRef(null) const wrapRef = useRef(null) const rendererRef = useRef(null) const tRef = useRef(0) const dirty = useRef(true) const [playing, setPlaying] = useState(false) const [time, setTime] = useState(0) const [theater, setTheater] = useState(false) const [started, setStarted] = useState(false) const [fps, setFps] = useState(0) useEffect(() => { if (!canvasRef.current) return rendererRef.current = new Renderer(canvasRef.current) // the master peaks above 0 dBFS (+0.49 dB): leave ~1 dB headroom so the browser doesn't clip it if (audioRef.current) audioRef.current.volume = 0.89 }, []) useEffect(() => { const r = rendererRef.current if (!r) return const hi = window.devicePixelRatio > 1.5 && Math.max(window.innerWidth, window.innerHeight) > 1100 const [w, h] = hi ? [1600, 900] : [1280, 720] if (orient === 'landscape') r.setSize(w, h) else r.setSize(h, w) dirty.current = true }, [orient]) useEffect(() => { if (ready) dirty.current = true }, [ready]) useEffect(() => { let raf = 0 let last = performance.now() let frames = 0 let lastUi = 0 const loop = (now: number) => { raf = requestAnimationFrame(loop) const a = audioRef.current const r = rendererRef.current if (!r || !a) return const isPlaying = !a.paused && !a.ended if (isPlaying) { tRef.current = a.currentTime dirty.current = true } if (dirty.current) { r.render(tRef.current) dirty.current = false frames++ } if (now - lastUi > 120) { setTime(tRef.current) lastUi = now } if (now - last > 1000) { setFps(isPlaying ? Math.round((frames * 1000) / (now - last)) : 0) frames = 0 last = now } } raf = requestAnimationFrame(loop) return () => cancelAnimationFrame(raf) }, []) const toggle = useCallback(() => { const a = audioRef.current if (!a) return setStarted(true) if (a.paused) { if (a.ended || a.currentTime >= DURATION - 0.05) a.currentTime = 0 a.play().catch(() => {}) } else a.pause() }, []) const seek = useCallback((t: number) => { const a = audioRef.current const v = Math.max(0, Math.min(DURATION, t)) tRef.current = v if (a) a.currentTime = v dirty.current = true setTime(v) }, []) useEffect(() => { bus.time = () => audioRef.current?.currentTime ?? tRef.current bus.seek = seek bus.play = () => { setStarted(true) audioRef.current?.play().catch(() => {}) } bus.pause = () => audioRef.current?.pause() const onLyrics = () => (dirty.current = true) window.addEventListener('mv-lyrics', onLyrics) return () => window.removeEventListener('mv-lyrics', onLyrics) }, [seek]) useEffect(() => { const onKey = (e: KeyboardEvent) => { if ((e.target as HTMLElement)?.closest('input,textarea')) return if (e.code === 'Space') { e.preventDefault() toggle() } else if (e.code === 'ArrowRight') seek(tRef.current + 5) else if (e.code === 'ArrowLeft') seek(tRef.current - 5) else if (e.code === 'Escape') setTheater(false) } window.addEventListener('keydown', onKey) return () => window.removeEventListener('keydown', onKey) }, [toggle, seek]) const fullscreen = () => { const el = wrapRef.current as (HTMLDivElement & { webkitRequestFullscreen?: () => void }) | null if (!el) return if (document.fullscreenElement) { document.exitFullscreen().catch(() => {}) return } if (el.requestFullscreen) el.requestFullscreen().catch(() => setTheater(true)) else if (el.webkitRequestFullscreen) el.webkitRequestFullscreen() else setTheater(true) } const scene = sceneAt(time) return (

01 在线观看

16:9 · 1080P
{!playing && ( )}
{fmt(time)} / {fmt(DURATION)}
{SCENES.map((s) => (
))}
seek(parseFloat(e.target.value))} aria-label="进度" />
{fps ? `${fps} fps` : ''} {theater && ( )}
{SCENES.map((s, i) => ( ))}
) } // ====================================================================== Export function ExportPanel({ orient, ready }: { orient: Orient; ready: boolean }) { const o: Orient = orient const [res, setRes] = useState<'1080' | '720'>('1080') const [fps, setFps] = useState<24 | 30 | 60>(30) const [state, setState] = useState<'idle' | 'running' | 'done' | 'error'>('idle') const [prog, setProg] = useState({ stage: '', progress: 0, eta: 0, frame: 0, total: 0 }) const [result, setResult] = useState<(ExportResult & { url: string; name: string }) | null>(null) const [err, setErr] = useState('') const ctrl = useRef(null) const supported = useMemo(() => (typeof window !== 'undefined' ? webCodecsSupported() : true), []) const size = useMemo(() => { const [a, b] = res === '1080' ? [1920, 1080] : [1280, 720] return o === 'landscape' ? [a, b] : [b, a] }, [o, res]) const start = async () => { if (!ready) return ctrl.current = new AbortController() setState('running') setErr('') if (result) URL.revokeObjectURL(result.url) setResult(null) try { const r = await exportMp4({ width: size[0], height: size[1], fps, signal: ctrl.current.signal, onProgress: (p) => setProg((prev) => ({ ...prev, ...p, eta: p.eta ?? prev.eta, frame: p.frame ?? prev.frame, total: p.total ?? prev.total })), }) const url = URL.createObjectURL(r.blob) const name = `黑街_BLACK-STREET_${size[0]}x${size[1]}_${fps}fps.${r.ext}` setResult({ ...r, url, name }) setState('done') download(url, name) } catch (e) { if ((e as Error).name === 'AbortError') setState('idle') else { setErr((e as Error).message || String(e)) setState('error') } } } const frames = Math.ceil(DURATION * fps) return (

03 导出 MP4 浏览器本地渲染 · 不上传

{([24, 30, 60] as const).map((f) => ( ))}
输出:{size[0]}×{size[1]} · {fps}fps · H.264 + AAC · 共 {frames.toLocaleString()} 帧 · 时长 {fmt(DURATION)} {!supported &&
当前浏览器不支持 WebCodecs 快速编码,将使用实时录制(需要约 2.5 分钟)。推荐使用最新版 Chrome / Edge。
}
{state !== 'running' ? ( ) : (
{prog.stage} {(prog.progress * 100).toFixed(1)}% {prog.total ? ` · ${prog.frame}/${prog.total} 帧` : ''} {prog.eta ? `预计剩余 ${fmt(prog.eta)}` : ''}

导出期间请保持本页面在前台,切到后台会变慢。

)} {state === 'error' &&
导出失败:{err}
} {state === 'done' && result && ( )}
) } // ====================================================================== Copy function CopyPanel({ toast }: { toast: (m: string) => void }) { const [pid, setPid] = useState(PLATFORMS[0].id) const p = PLATFORMS.find((x) => x.id === pid)! const [titles, setTitles] = useState>(() => Object.fromEntries(PLATFORMS.map((x) => [x.id, x.titles[0]]))) const [descs, setDescs] = useState>(() => Object.fromEntries(PLATFORMS.map((x) => [x.id, x.desc]))) const [tags, setTags] = useState>(() => Object.fromEntries(PLATFORMS.map((x) => [x.id, [...x.tags]]))) const [newTag, setNewTag] = useState('') const title = titles[pid] const tcount = countChars(title) const myTags = tags[pid] const allTags = useMemo(() => Array.from(new Set([...p.tags, ...myTags])), [p, myTags]) const overTitle = tcount > p.titleLimit const overTags = p.tagLimit != null && myTags.length > p.tagLimit const doCopy = async (text: string, what: string) => { const ok = await copyText(text) toast(ok ? `已复制${what}` : '复制失败,请手动选择文本') } const toggleTag = (t: string) => setTags((prev) => ({ ...prev, [pid]: prev[pid].includes(t) ? prev[pid].filter((x) => x !== t) : [...prev[pid], t] })) const addTag = () => { const t = newTag.replace(/^#/, '').trim() if (!t) return setTags((prev) => ({ ...prev, [pid]: prev[pid].includes(t) ? prev[pid] : [...prev[pid], t] })) setNewTag('') } const tagText = formatTags(p, myTags) return (

04 发布文案 标题 · 描述 · 话题,一键复制

{PLATFORMS.map((x) => ( ))}
{p.tip}
{tcount}/{p.titleLimit} 字
setTitles((prev) => ({ ...prev, [pid]: e.target.value }))} />
{p.titles.map((t) => ( ))}
{countChars(descs[pid])} 字