mx / dengtaishan-src /src /app /PlayerView.tsx
Ethscriptions's picture
登泰山记:渲染引擎、九个篇章场景、程序化配乐音效、MP4 导出、发布文案与封面(初版)
6fff8e3 verified
Raw History Blame Contribute Delete
10.3 kB
// 视频预览播放器
import { useCallback, useEffect, useRef, useState } from 'react'
import { Renderer } from '../video/render'
import { AudioClock } from '../video/player'
import { TL, DURATION, sceneIndexAt } from '../video/timeline'
import { loadVoices, renderSegment } from '../video/audio'
import { cx, fmtTime, Switch } from './ui'
const CH_LABEL: Record<string, string> = {
prologue: '序章', shot1: '镜头一 航拍', shot2: '镜头二 跟拍', shot3: '镜头三 延时', shot4: '镜头四 特写', shot5: '镜头五 空镜', depth: '深读', recite: '背诵', epilogue: '尾声',
}
export default function PlayerView({ orient, setOrient, ready }: { orient: 'l' | 'p'; setOrient: (o: 'l' | 'p') => void; ready: boolean }) {
const wrapRef = useRef<HTMLDivElement>(null)
const boxRef = useRef<HTMLDivElement>(null)
const canvasRef = useRef<HTMLCanvasElement>(null)
const rendRef = useRef<Renderer | null>(null)
const clockRef = useRef<AudioClock>(new AudioClock())
const dirty = useRef(true)
const [t, setT] = useState(0)
const [playing, setPlaying] = useState(false)
const [buffering, setBuffering] = useState(false)
const [music, setMusic] = useState(true)
const [vol, setVol] = useState(1)
const [size, setSize] = useState<[number, number]>([0, 0])
const [voicePct, setVoicePct] = useState(0)
useEffect(() => {
loadVoices((p) => setVoicePct(p))
.then(() => renderSegment(0, true))
.catch(() => undefined)
const c = clockRef.current
c.onEnded = () => setPlaying(false)
c.onBuffering = (b) => setBuffering(b)
return () => c.dispose()
}, [])
// 画布尺寸
useEffect(() => {
const el = boxRef.current
if (!el) return
let tm: number | undefined
const ro = new ResizeObserver(() => {
clearTimeout(tm)
tm = window.setTimeout(() => {
const r = el.getBoundingClientRect()
const dpr = Math.min(window.devicePixelRatio || 1, 2)
let w = Math.round(r.width * dpr)
let h = Math.round(r.height * dpr)
const cap = orient === 'l' ? [1920, 1080] : [1080, 1920]
const k = Math.min(1, cap[0] / w, cap[1] / h)
w = Math.round(w * k)
h = Math.round(h * k)
setSize((s) => (s[0] === w && s[1] === h ? s : [w, h]))
}, 120)
})
ro.observe(el)
return () => {
ro.disconnect()
clearTimeout(tm)
}
}, [orient])
useEffect(() => {
if (!size[0] || !ready) return
const c = canvasRef.current!
c.width = size[0]
c.height = size[1]
rendRef.current?.dispose()
rendRef.current = new Renderer(size[0], size[1])
dirty.current = true
// 空闲时预热各场景素材,避免播放时卡顿
const r = rendRef.current
const scratch = document.createElement('canvas')
scratch.width = size[0]
scratch.height = size[1]
const sg = scratch.getContext('2d')!
const times = TL.scenes.flatMap((s) => [s.start + s.intro + 1, s.start + s.dur * 0.6])
let i = 0
let cancel = false
const step = () => {
if (cancel || i >= times.length || rendRef.current !== r) return
if (!clockRef.current.playing) r.render(sg, times[i++])
setTimeout(step, 60)
}
const id = window.setTimeout(step, 800)
return () => {
cancel = true
clearTimeout(id)
}
}, [size, ready])
// 渲染循环
useEffect(() => {
let raf = 0
let lastUi = 0
const loop = (now: number) => {
raf = requestAnimationFrame(loop)
const r = rendRef.current
const c = canvasRef.current
if (!r || !c) return
const clock = clockRef.current
if (clock.playing || dirty.current) {
const tt = clock.now()
r.render(c.getContext('2d')!, tt)
dirty.current = false
if (now - lastUi > 120) {
lastUi = now
setT(tt)
}
}
}
raf = requestAnimationFrame(loop)
return () => cancelAnimationFrame(raf)
}, [])
const toggle = useCallback(async () => {
const c = clockRef.current
if (c.playing) {
c.pause()
setPlaying(false)
setT(c.now())
} else {
setPlaying(true)
try {
await c.play()
} catch (e) {
console.error(e)
setPlaying(false)
}
}
}, [])
const seek = useCallback((v: number) => {
clockRef.current.seek(v)
setT(v)
dirty.current = true
}, [])
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
const tag = (e.target as HTMLElement)?.tagName
if (tag === 'INPUT' || tag === 'TEXTAREA') return
if (e.code === 'Space') {
e.preventDefault()
toggle()
} else if (e.code === 'ArrowRight') seek(clockRef.current.now() + 5)
else if (e.code === 'ArrowLeft') seek(clockRef.current.now() - 5)
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [toggle, seek])
const fs = () => {
const el = wrapRef.current as (HTMLElement & { webkitRequestFullscreen?: () => void }) | null
if (!el) return
if (document.fullscreenElement) document.exitFullscreen()
else if (el.requestFullscreen) el.requestFullscreen()
else el.webkitRequestFullscreen?.()
}
const cur = sceneIndexAt(t)
return (
<div className="flex flex-col gap-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-2 rounded-full border border-white/10 p-1">
{(['l', 'p'] as const).map((o) => (
<button
key={o}
onClick={() => setOrient(o)}
className={cx('h-8 px-4 rounded-full text-[13px] transition-colors', orient === o ? 'bg-[#c9a86a] text-[#16130e] font-semibold' : 'text-[#cfc8bb] hover:text-white')}
>
{o === 'l' ? '横屏 16:9' : '竖屏 9:16 · 手机'}
</button>
))}
</div>
<div className="flex items-center gap-5">
<Switch on={music} onChange={(v) => { setMusic(v); clockRef.current.setMusic(v) }} label="背景音乐" />
<label className="hidden sm:flex items-center gap-2 text-[13px] text-[#a39d92]">
音量
<input type="range" min={0} max={1} step={0.05} value={vol} onChange={(e) => { const v = Number(e.target.value); setVol(v); clockRef.current.setVolume(v) }} className="w-24 accent-[#c9a86a]" />
</label>
</div>
</div>
<div ref={wrapRef} className="relative mx-auto w-full bg-black overflow-hidden rounded-xl ring-1 ring-white/10 shadow-[0_30px_120px_-30px_rgba(201,168,106,0.25)]" style={orient === 'p' ? { width: 'min(100%, 460px, calc(80vh * 0.5625))' } : undefined}>
<div ref={boxRef} className="relative w-full" style={{ aspectRatio: orient === 'l' ? '16 / 9' : '9 / 16' }}>
<canvas ref={canvasRef} className="absolute inset-0 h-full w-full" onClick={toggle} />
{(!ready || buffering) && (
<div className="absolute inset-0 flex items-center justify-center bg-black/40 pointer-events-none">
<div className="rounded-full bg-black/60 px-4 py-2 text-[13px] text-[#e8e0d0]">{!ready ? '正在加载字体…' : `正在合成声音… ${voicePct < 1 ? Math.round(voicePct * 100) + '%' : ''}`}</div>
</div>
)}
{ready && !playing && !buffering && (
<button onClick={toggle} aria-label="播放" className="absolute inset-0 m-auto h-20 w-20 rounded-full bg-black/45 backdrop-blur ring-1 ring-[#c9a86a]/70 flex items-center justify-center hover:bg-black/60 transition-colors">
<svg width="30" height="30" viewBox="0 0 24 24" fill="#f3e6c8"><path d="M8 5v14l11-7z" /></svg>
</button>
)}
</div>
{/* 控制条 */}
<div className="flex items-center gap-3 px-3 sm:px-4 py-3 bg-[#0d0d10]">
<button onClick={toggle} className="h-9 w-9 shrink-0 rounded-full bg-[#c9a86a] text-[#16130e] flex items-center justify-center" aria-label={playing ? '暂停' : '播放'}>
{playing ? <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M6 5h4v14H6zM14 5h4v14h-4z" /></svg> : <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z" /></svg>}
</button>
<div className="relative flex-1 h-9 flex items-center">
<div className="absolute inset-x-0 top-1/2 -translate-y-1/2 h-1.5 rounded-full bg-white/10 overflow-hidden">
<div className="h-full bg-[#c9a86a]" style={{ width: `${(t / DURATION) * 100}%` }} />
</div>
{TL.scenes.slice(1).map((s) => (
<div key={s.id} className="absolute top-1/2 -translate-y-1/2 h-3 w-px bg-white/40" style={{ left: `${(s.start / DURATION) * 100}%` }} />
))}
<input type="range" min={0} max={DURATION} step={0.05} value={t} onChange={(e) => seek(Number(e.target.value))} className="absolute inset-0 w-full opacity-0 cursor-pointer" aria-label="进度" />
</div>
<div className="shrink-0 font-mono text-[12px] text-[#a39d92] tabular-nums">{fmtTime(t)} / {fmtTime(DURATION)}</div>
<button onClick={fs} className="shrink-0 h-9 w-9 rounded-full border border-white/15 text-[#ddd6c9] flex items-center justify-center hover:border-[#c9a86a]" aria-label="全屏">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5" /></svg>
</button>
</div>
</div>
<div className="flex gap-2 overflow-x-auto pb-1 -mx-1 px-1">
{TL.scenes.map((s, i) => (
<button
key={s.id}
onClick={() => seek(s.start + 0.01)}
className={cx('shrink-0 rounded-lg border px-3 py-2 text-left transition-colors', i === cur ? 'border-[#c9a86a] bg-[#c9a86a]/10' : 'border-white/10 hover:border-white/30')}
>
<div className="text-[11px] text-[#8f897e] tabular-nums">{fmtTime(s.start)}</div>
<div className={cx('text-[13px] whitespace-nowrap', i === cur ? 'text-[#f3e6c8]' : 'text-[#cfc8bb]')}>{CH_LABEL[s.id]}</div>
</button>
))}
</div>
</div>
)
}