feat: 优化歌词视觉效果

This commit is contained in:
yhlhoh committed 2026-11-11 21:40:57 +08:00
1 parent 82b1fa0d47
commit 60fbbced7d
6 files changed
+532 -47

No files matched your search

+14 -1
View File
@@ -86,6 +86,11 @@ OBS 中添加 **浏览器源(Browser Source)**,URL 填 `http://127.0.0.1:3
- 位置(顶部/居中/底部)、水平对齐。 - 位置(顶部/居中/底部)、水平对齐。
- 入场动画:淡入 / 上滑 / 缩放 / 模糊 / 弹跳 / **自定义(写 CSS)** / 无。 - 入场动画:淡入 / 上滑 / 缩放 / 模糊 / 弹跳 / **自定义(写 CSS)** / 无。
- **入场时长**(`enterDurationMs`):让模糊、缩放等入场动画放慢,默认 300ms,模糊入场一般 1200–1800ms 更舒服。
- **入场模糊半径**(`blurPx`):模糊入场与模糊出场共用的最大模糊半径,默认 10px。
- **入场后回缩**:入场动画播完后,文字在 `shrinkDurationMs` 内缓慢缩放到 `holdShrinkTo` 倍(1 = 不回缩)。例如 0.94 + 3000ms 就是「缓缓回缩」。控件里有「轻微回缩」快捷按钮。
- **自动适配单句时长**:入场时长 + 回缩时长会与「到下一句的间隔」自动协商。间隔不够时,入场最多占 45%,回缩占用剩余时间(至少 120ms),保证每句都能完整播完入场→回缩,不会出现「回缩刚开始就跳到下一句」。最后一句按「末句停留」计算。
- **出场动画**(`outro`):整段字幕结束时播放,可选 淡出 / 模糊消散 / 下滑淡出 / 上浮淡出 / 缩小淡出 / 自定义 / 无,配套 **出场时长**(`outDurationMs`,默认 260ms)。手动点「停止」也会走完整的出场动画。
- 字号、字重、字间距、行高、文字颜色。 - 字号、字重、字间距、行高、文字颜色。
- 字体:常用字体快捷选择 + 自定义 CSS `font-family`。注意 OBS 所在电脑需要安装对应字体,否则回退到系统字体。 - 字体:常用字体快捷选择 + 自定义 CSS `font-family`。注意 OBS 所在电脑需要安装对应字体,否则回退到系统字体。
- 背景:支持 `rgba()` / `transparent`,可用「显示背景」开关一键禁用(保留颜色配置)。 - 背景:支持 `rgba()` / `transparent`,可用「显示背景」开关一键禁用(保留颜色配置)。
@@ -96,7 +101,15 @@ OBS 中添加 **浏览器源(Browser Source)**,URL 填 `http://127.0.0.1:3
- 内边距、圆角、最大宽度、距画面边缘距离、下一句缩放/颜色。 - 内边距、圆角、最大宽度、距画面边缘距离、下一句缩放/颜色。
- **自定义 CSS**:见下一节。 - **自定义 CSS**:见下一节。
右侧有 16:9 样式预览和「试播本段」,可直接查看本段字幕的实际节奏、逐字点亮和自定义动画。 每条字幕的生命周期是三个阶段,可以用 CSS 钩子分别定制:
| 阶段 | 状态类 | 默认行为 |
| --- | --- | --- |
| 入场 | `.lrc-state-entering` | 播放所选入场动画,时长 = `enterDurationMs` |
| 停留 | `.lrc-state-hold` | 保持可读,同时在 `shrinkDurationMs` 内回缩到 `holdShrinkTo` |
| 出场 | `.lrc-state-leaving` + `.lrc-out-*` | 播放所选出场动画,时长 = `outDurationMs`,结束后隐藏 |
右侧有 16:9 样式预览和「试播本段」,可直接看到入场 → 回缩 → 出场的完整时序;「循环」开着时会反复重播,方便调时长。
### 7. 自定义动画 / 修饰(CSS) ### 7. 自定义动画 / 修饰(CSS)
+17
View File
@@ -23,6 +23,7 @@ const DEFAULT_CREDIT_KEYWORDS = [
const LRC_POSITIONS = ['top', 'center', 'bottom']; const LRC_POSITIONS = ['top', 'center', 'bottom'];
const LRC_ALIGNS = ['left', 'center', 'right']; const LRC_ALIGNS = ['left', 'center', 'right'];
const LRC_ANIMATIONS = ['none', 'fade', 'slide', 'zoom', 'blur', 'bounce', 'custom']; const LRC_ANIMATIONS = ['none', 'fade', 'slide', 'zoom', 'blur', 'bounce', 'custom'];
const LRC_OUTROS = ['none', 'fade', 'blur', 'slideDown', 'slideUp', 'zoom', 'custom'];
const DEFAULT_LRC_FILTERS = { const DEFAULT_LRC_FILTERS = {
dropCreditLines: true, dropCreditLines: true,
@@ -49,6 +50,15 @@ const DEFAULT_LRC_STYLE = {
textShadow: '0 2px 12px rgba(0, 0, 0, 0.85)', textShadow: '0 2px 12px rgba(0, 0, 0, 0.85)',
textShadowEnabled: true, textShadowEnabled: true,
animation: 'fade', animation: 'fade',
// 入场时长(ms):模糊/缩放等动画跑得更久一些更适合直播画面
enterDurationMs: 300,
// 回缩:入场动画结束后,文字缓慢缩小到 holdShrinkTo 倍(1 = 不回缩)
holdShrinkTo: 1,
shrinkDurationMs: 0,
blurPx: 10,
// 出场:整段字幕结束时播放
outro: 'fade',
outDurationMs: 260,
// 自定义 CSS / 自定义动画:作用于 .lrc-layer / .lrc-box / .lrc-text / .lrc-word // 自定义 CSS / 自定义动画:作用于 .lrc-layer / .lrc-box / .lrc-text / .lrc-word
customCss: '', customCss: '',
showNextLine: true, showNextLine: true,
@@ -473,6 +483,7 @@ function normalizeStyle(input) {
if (LRC_POSITIONS.includes(src.position)) style.position = src.position; if (LRC_POSITIONS.includes(src.position)) style.position = src.position;
if (LRC_ALIGNS.includes(src.align)) style.align = src.align; if (LRC_ALIGNS.includes(src.align)) style.align = src.align;
if (LRC_ANIMATIONS.includes(src.animation)) style.animation = src.animation; if (LRC_ANIMATIONS.includes(src.animation)) style.animation = src.animation;
if (LRC_OUTROS.includes(src.outro)) style.outro = src.outro;
if (typeof src.fontFamily === 'string' && src.fontFamily.trim()) { if (typeof src.fontFamily === 'string' && src.fontFamily.trim()) {
style.fontFamily = cleanString(src.fontFamily, 200); style.fontFamily = cleanString(src.fontFamily, 200);
} }
@@ -493,6 +504,11 @@ function normalizeStyle(input) {
style.maxWidthPercent = clampNumber(src.maxWidthPercent, 20, 100, style.maxWidthPercent); style.maxWidthPercent = clampNumber(src.maxWidthPercent, 20, 100, style.maxWidthPercent);
style.nextLineScale = clampNumber(src.nextLineScale, 0.3, 1, style.nextLineScale); style.nextLineScale = clampNumber(src.nextLineScale, 0.3, 1, style.nextLineScale);
style.bottomOffsetVh = clampNumber(src.bottomOffsetVh, 0, 45, style.bottomOffsetVh); style.bottomOffsetVh = clampNumber(src.bottomOffsetVh, 0, 45, style.bottomOffsetVh);
style.enterDurationMs = clampNumber(src.enterDurationMs, 0, 10000, style.enterDurationMs);
style.outDurationMs = clampNumber(src.outDurationMs, 0, 10000, style.outDurationMs);
style.shrinkDurationMs = clampNumber(src.shrinkDurationMs, 0, 20000, style.shrinkDurationMs);
style.holdShrinkTo = clampNumber(src.holdShrinkTo, 0.3, 1, style.holdShrinkTo);
style.blurPx = clampNumber(src.blurPx, 0, 60, style.blurPx);
style.showNextLine = src.showNextLine !== false; style.showNextLine = src.showNextLine !== false;
style.backgroundEnabled = src.backgroundEnabled !== false; style.backgroundEnabled = src.backgroundEnabled !== false;
style.textShadowEnabled = src.textShadowEnabled !== false; style.textShadowEnabled = src.textShadowEnabled !== false;
@@ -542,6 +558,7 @@ module.exports = {
LRC_POSITIONS, LRC_POSITIONS,
LRC_ALIGNS, LRC_ALIGNS,
LRC_ANIMATIONS, LRC_ANIMATIONS,
LRC_OUTROS,
MAX_SOURCE_CHARS, MAX_SOURCE_CHARS,
parseLrc, parseLrc,
parseTimestamp, parseTimestamp,
+105 -17
View File
@@ -1,29 +1,86 @@
/* LRC 字幕运行时样式:管理页预览与 OBS widget 共用 */ /* LRC 字幕运行时样式:管理页预览与 OBS widget 共用
*
* 状态类统一挂在 .lrc-layer 上(lrc-state-entering / hold / leaving),
* 动画目标统一是 .lrc-text,两者之间隔着 .lrc-box,所以用后代选择器。
*
* 时间参数由页面通过 CSS 变量注入(带兜底默认值):
* --lrc-in-dur 入场时长(ms)
* --lrc-out-dur 出场时长(ms)
* --lrc-shrink-dur 入场结束后的缓慢回缩时长(ms)
* --lrc-shrink-to 回缩后的缩放比例(1 = 不回缩)
* --lrc-blur-px 模糊入场/出场时的最大模糊半径(px)
*/
/* ── 进场动画 ───────────────────────────────────────────────────────────── */ /* ── 入场:状态类驱动,时长可调 ─────────────────────────────────────────── */
.lrc-anim-fade .lrc-text { .lrc-layer.lrc-state-entering .lrc-text {
animation: lrcFadeIn 0.22s ease both; animation-duration: var(--lrc-in-dur, 300ms);
animation-timing-function: ease;
animation-fill-mode: both;
} }
.lrc-anim-slide .lrc-text { .lrc-layer.lrc-anim-fade.lrc-state-entering .lrc-text {
animation: lrcSlideIn 0.24s cubic-bezier(0.2, 0.8, 0.3, 1) both; animation-name: lrcFadeIn;
} }
.lrc-anim-zoom .lrc-text { .lrc-layer.lrc-anim-slide.lrc-state-entering .lrc-text {
animation: lrcZoomIn 0.26s cubic-bezier(0.2, 0.9, 0.3, 1.15) both; animation-name: lrcSlideIn;
animation-timing-function: cubic-bezier(0.2, 0.8, 0.3, 1);
} }
.lrc-anim-blur .lrc-text { .lrc-layer.lrc-anim-zoom.lrc-state-entering .lrc-text {
animation: lrcBlurIn 0.3s ease both; animation-name: lrcZoomIn;
animation-timing-function: cubic-bezier(0.2, 0.9, 0.3, 1.15);
} }
.lrc-anim-bounce .lrc-text { .lrc-layer.lrc-anim-blur.lrc-state-entering .lrc-text {
animation: lrcBounceIn 0.42s cubic-bezier(0.2, 0.9, 0.3, 1.2) both; animation-name: lrcBlurIn;
}
.lrc-layer.lrc-anim-bounce.lrc-state-entering .lrc-text {
animation-name: lrcBounceIn;
animation-timing-function: cubic-bezier(0.2, 0.9, 0.3, 1.2);
} }
/* lrc-anim-custom:不内置动画,由「自定义 CSS」定义,例如: /* lrc-anim-custom:不内置动画,由「自定义 CSS」定义,例如:
.lrc-layer.lrc-anim-custom .lrc-text { animation: myAnim .5s ease both; } .lrc-layer.lrc-anim-custom.lrc-state-entering .lrc-text { animation: myAnim .5s ease both; }
@keyframes myAnim { from { opacity: 0; transform: translateY(18px) scale(.96); } } @keyframes myAnim { from { opacity: 0; transform: translateY(18px) scale(.96); } }
*/ */
.lrc-anim-none .lrc-text { .lrc-layer.lrc-anim-none.lrc-state-entering .lrc-text,
animation: none; .lrc-layer.lrc-anim-custom.lrc-state-entering .lrc-text {
animation-name: none;
} }
/* 入场结束后:缓慢回缩(scale 走 transform,不干扰逐字的颜色/发光) */
.lrc-layer.lrc-state-hold .lrc-text {
transform: scale(var(--lrc-shrink-to, 1));
transform-origin: center;
transition: transform var(--lrc-shrink-dur, 0ms) linear;
}
/* ── 出场 ───────────────────────────────────────────────────────────────── */
.lrc-layer.lrc-state-leaving .lrc-text {
animation-duration: var(--lrc-out-dur, 260ms);
animation-timing-function: ease;
animation-fill-mode: both;
}
.lrc-layer.lrc-out-fade.lrc-state-leaving .lrc-text {
animation-name: lrcOutFade;
}
.lrc-layer.lrc-out-slideDown.lrc-state-leaving .lrc-text {
animation-name: lrcOutSlideDown;
animation-timing-function: cubic-bezier(0.4, 0, 0.6, 1);
}
.lrc-layer.lrc-out-slideUp.lrc-state-leaving .lrc-text {
animation-name: lrcOutSlideUp;
animation-timing-function: cubic-bezier(0.4, 0, 0.6, 1);
}
.lrc-layer.lrc-out-zoom.lrc-state-leaving .lrc-text {
animation-name: lrcOutZoom;
}
.lrc-layer.lrc-out-blur.lrc-state-leaving .lrc-text {
animation-name: lrcOutBlur;
}
/* lrc-out-custom:由「自定义 CSS」定义出场动画 */
.lrc-layer.lrc-out-none.lrc-state-leaving .lrc-text,
.lrc-layer.lrc-out-custom.lrc-state-leaving .lrc-text {
animation-name: none;
}
/* ── 关键帧 ─────────────────────────────────────────────────────────────── */
@keyframes lrcFadeIn { @keyframes lrcFadeIn {
from { opacity: 0; } from { opacity: 0; }
to { opacity: 1; } to { opacity: 1; }
@@ -37,8 +94,10 @@
to { opacity: 1; transform: scale(1); } to { opacity: 1; transform: scale(1); }
} }
@keyframes lrcBlurIn { @keyframes lrcBlurIn {
from { opacity: 0; filter: blur(10px); } 0% { opacity: 0; filter: blur(var(--lrc-blur-px, 10px)); }
to { opacity: 1; filter: blur(0); } 30% { opacity: 0.32; }
45% { opacity: 0.55; filter: blur(calc(var(--lrc-blur-px, 10px) * 0.55)); }
100% { opacity: 1; filter: blur(0px); }
} }
@keyframes lrcBounceIn { @keyframes lrcBounceIn {
0% { opacity: 0; transform: translateY(22px) scale(0.94); } 0% { opacity: 0; transform: translateY(22px) scale(0.94); }
@@ -46,6 +105,35 @@
100% { opacity: 1; transform: translateY(0) scale(1); } 100% { opacity: 1; transform: translateY(0) scale(1); }
} }
@keyframes lrcOutFade {
from { opacity: 1; }
to { opacity: 0; }
}
@keyframes lrcOutSlideDown {
from { opacity: 1; transform: translateY(0); }
to { opacity: 0; transform: translateY(14px); }
}
@keyframes lrcOutSlideUp {
from { opacity: 1; transform: translateY(0); }
to { opacity: 0; transform: translateY(-12px); }
}
@keyframes lrcOutZoom {
from { opacity: 1; transform: scale(1); }
to { opacity: 0; transform: scale(0.92); }
}
@keyframes lrcOutBlur {
0% { opacity: 1; filter: blur(0px); }
/* 一开始就快速起糊,避免前段看起来「没动静」 */
25% { opacity: 0.92; filter: blur(calc(var(--lrc-blur-px, 10px) * 0.35)); }
60% { opacity: 0.55; filter: blur(calc(var(--lrc-blur-px, 10px) * 0.72)); }
100% { opacity: 0; filter: blur(var(--lrc-blur-px, 10px)); }
}
/* 系统开启「减少动态效果」时收窄过渡,避免不适 */
@media (prefers-reduced-motion: reduce) {
.lrc-layer.lrc-state-hold .lrc-text { transition-duration: 1ms; }
}
/* ── 逐字(增强型 LRC) ─────────────────────────────────────────────────── */ /* ── 逐字(增强型 LRC) ─────────────────────────────────────────────────── */
.lrc-text .lrc-word { .lrc-text .lrc-word {
color: var(--lrc-karaoke-pending, rgba(255, 255, 255, 0.45)); color: var(--lrc-karaoke-pending, rgba(255, 255, 255, 0.45));
+177 -9
View File
@@ -659,10 +659,83 @@
<Select.Option value="none">无</Select.Option> <Select.Option value="none">无</Select.Option>
</Select> </Select>
</StyleField> </StyleField>
<StyleField label="显示下一句"> <StyleField label="显示下一句">
<Switch checked={style.showNextLine !== false} onChange={v => set({ showNextLine: v })} /> <Switch checked={style.showNextLine !== false} onChange={v => set({ showNextLine: v })} />
</StyleField> </StyleField>
<StyleField label="入场时长 (ms)">
<InputNumber
min={0} max={10000} step={50}
value={style.enterDurationMs}
onChange={v => set({ enterDurationMs: v == null ? 300 : v })}
style={{ width: '100%' }}
/>
</StyleField>
<StyleField label="入场模糊半径 (px,模糊/出场用)">
<InputNumber
min={0} max={60} step={1}
value={style.blurPx}
onChange={v => set({ blurPx: v == null ? 10 : v })}
style={{ width: '100%' }}
/>
</StyleField>
<StyleField label="出场动画">
<Select value={style.outro} onChange={v => set({ outro: v })} style={{ width: '100%' }}>
<Select.Option value="fade">淡出</Select.Option>
<Select.Option value="blur">模糊消散</Select.Option>
<Select.Option value="slideDown">下滑淡出</Select.Option>
<Select.Option value="slideUp">上浮淡出</Select.Option>
<Select.Option value="zoom">缩小淡出</Select.Option>
<Select.Option value="custom">自定义(写 CSS)</Select.Option>
<Select.Option value="none">无</Select.Option>
</Select>
</StyleField>
<StyleField label="出场时长 (ms)">
<InputNumber
min={0} max={10000} step={50}
value={style.outDurationMs}
onChange={v => set({ outDurationMs: v == null ? 260 : v })}
style={{ width: '100%' }}
/>
</StyleField>
<StyleField label="入场后回缩到 (1 = 不回缩)">
<InputNumber
min={0.3} max={1} step={0.01}
value={style.holdShrinkTo}
onChange={v => set({ holdShrinkTo: v == null ? 1 : v })}
style={{ width: '100%' }}
/>
</StyleField>
<StyleField label="回缩时长 (ms)">
<InputNumber
min={0} max={20000} step={100}
value={style.shrinkDurationMs}
onChange={v => set({ shrinkDurationMs: v == null ? 0 : v })}
style={{ width: '100%' }}
/>
</StyleField>
<StyleField label="回缩效果">
<Space style={{ height: 32 }}>
<Button
size="small"
onClick={() => set({ holdShrinkTo: 0.92, shrinkDurationMs: 1200 })}
>轻微回缩</Button>
<Button
size="small"
onClick={() => set({ holdShrinkTo: 1, shrinkDurationMs: 0 })}
disabled={Number(style.holdShrinkTo) === 1}
>关闭</Button>
</Space>
</StyleField>
<StyleField label="当前效果预览">
<Text style={{ color: '#888', fontSize: 12 }}>
入场 {Number(style.enterDurationMs || 0)}ms → 回缩到 {Number(style.holdShrinkTo || 1)}({Number(style.shrinkDurationMs || 0)}ms)
→ 出场 {Number(style.outDurationMs || 0)}ms
</Text>
</StyleField>
<StyleField label="显示背景"> <StyleField label="显示背景">
<Switch <Switch
checked={style.backgroundEnabled !== false} checked={style.backgroundEnabled !== false}
@@ -790,7 +863,9 @@
); );
} }
function LrcPreviewStage({ style, cue, text, nextText, playing, elapsed }) { const LRC_OUTRO_OPTIONS = ['none', 'fade', 'blur', 'slideDown', 'slideUp', 'zoom', 'custom'];
function LrcPreviewStage({ style, cue, text, nextText, playing, elapsed, phase, configKey, fittedTiming }) {
const scale = 0.42; const scale = 0.42;
const alignItems = style.position === 'top' ? 'flex-start' : (style.position === 'center' ? 'center' : 'flex-end'); const alignItems = style.position === 'top' ? 'flex-start' : (style.position === 'center' ? 'center' : 'flex-end');
const justifyContent = style.align === 'left' ? 'flex-start' : (style.align === 'right' ? 'flex-end' : 'center'); const justifyContent = style.align === 'left' ? 'flex-start' : (style.align === 'right' ? 'flex-end' : 'center');
@@ -806,9 +881,19 @@
}); });
} }
const outro = LRC_OUTRO_OPTIONS.includes(style.outro) ? style.outro : 'fade';
const hideText = phase === 'leaving' && outro === 'none';
// 传入的 phaseTiming 由播放循环按当前句间隔算好(入场+回缩必须塞进单句时长)
const phaseTiming = fittedTiming || {
enterMs: Number(style.enterDurationMs || 0),
shrinkMs: Number(style.shrinkDurationMs || 0)
};
const phaseKey = (cue ? cue.t : 'empty') + '|' + (phase || 'alpha') + '|' + configKey
+ '|' + phaseTiming.enterMs + '|' + phaseTiming.shrinkMs;
return ( return (
<div <div
className={'lrc-preview-layer lrc-layer lrc-anim-' + (style.animation || 'fade')} className={'lrc-preview-layer lrc-layer lrc-anim-' + (style.animation || 'fade')
+ ' lrc-out-' + outro + (phase ? ' lrc-state-' + phase : '')}
style={{ style={{
position: 'relative', width: '100%', aspectRatio: '16/9', position: 'relative', width: '100%', aspectRatio: '16/9',
background: 'linear-gradient(135deg, #141826, #05070c)', background: 'linear-gradient(135deg, #141826, #05070c)',
@@ -817,7 +902,12 @@
paddingTop: style.position === 'top' ? edge : 0, paddingTop: style.position === 'top' ? edge : 0,
paddingBottom: style.position === 'bottom' ? edge : 0, paddingBottom: style.position === 'bottom' ? edge : 0,
paddingLeft: 18, paddingRight: 18, paddingLeft: 18, paddingRight: 18,
boxSizing: 'border-box' boxSizing: 'border-box',
'--lrc-in-dur': Number(phaseTiming.enterMs) + 'ms',
'--lrc-out-dur': Number(style.outDurationMs || 0) + 'ms',
'--lrc-shrink-dur': Number(phaseTiming.shrinkMs) + 'ms',
'--lrc-shrink-to': String(style.holdShrinkTo == null ? 1 : style.holdShrinkTo),
'--lrc-blur-px': Number(style.blurPx == null ? 10 : style.blurPx) + 'px'
}} }}
> >
<div <div
@@ -832,7 +922,7 @@
}} }}
> >
<div <div
key={cue ? cue.t : 'empty'} key={phaseKey}
className="lrc-text" className="lrc-text"
style={{ style={{
whiteSpace: 'pre-line', wordBreak: 'break-word', whiteSpace: 'pre-line', wordBreak: 'break-word',
@@ -843,6 +933,7 @@
letterSpacing: (style.letterSpacing || 0) * scale + 'px', letterSpacing: (style.letterSpacing || 0) * scale + 'px',
lineHeight: style.lineHeight, lineHeight: style.lineHeight,
textShadow: shadow, textShadow: shadow,
visibility: hideText ? 'hidden' : 'visible',
'--lrc-color': style.color, '--lrc-color': style.color,
'--lrc-karaoke-pending': style.karaokePendingColor || 'rgba(255, 255, 255, 0.45)' '--lrc-karaoke-pending': style.karaokePendingColor || 'rgba(255, 255, 255, 0.45)'
}} }}
@@ -857,8 +948,9 @@
)) ))
: (text || '(字幕预览)')} : (text || '(字幕预览)')}
</div> </div>
{style.showNextLine !== false && nextText ? ( {style.showNextLine !== false && nextText && outro !== 'none' ? (
<div <div
key={'next-' + phaseKey}
className="lrc-next" className="lrc-next"
style={{ style={{
marginTop: 3, whiteSpace: 'pre-line', wordBreak: 'break-word', marginTop: 3, whiteSpace: 'pre-line', wordBreak: 'break-word',
@@ -901,6 +993,8 @@
const [previewRun, setPreviewRun] = React.useState(0); const [previewRun, setPreviewRun] = React.useState(0);
const [previewIndex, setPreviewIndex] = React.useState(-1); const [previewIndex, setPreviewIndex] = React.useState(-1);
const [previewElapsed, setPreviewElapsed] = React.useState(0); const [previewElapsed, setPreviewElapsed] = React.useState(0);
const [previewPhase, setPreviewPhase] = React.useState(null);
const [previewLoop, setPreviewLoop] = React.useState(true);
const [nowTick, setNowTick] = React.useState(Date.now()); const [nowTick, setNowTick] = React.useState(Date.now());
const fileRef = React.useRef(null); const fileRef = React.useRef(null);
const initializedRef = React.useRef(false); const initializedRef = React.useRef(false);
@@ -1012,6 +1106,7 @@
setPreviewPlaying(false); setPreviewPlaying(false);
setPreviewIndex(-1); setPreviewIndex(-1);
setPreviewElapsed(0); setPreviewElapsed(0);
setPreviewPhase(null);
}, [configKey]); }, [configKey]);
React.useEffect(() => { React.useEffect(() => {
@@ -1021,9 +1116,35 @@
setPreviewPlaying(false); setPreviewPlaying(false);
return undefined; return undefined;
} }
const style = draft.style || {};
const baseEnterMs = Math.max(0, Number(style.enterDurationMs) || 0);
const baseShrinkMs = Math.max(0, Number(style.shrinkDurationMs) || 0);
const outMs = Math.max(0, Number(style.outDurationMs) || 0);
const outro = LRC_OUTRO_OPTIONS.includes(style.outro) ? style.outro : 'fade';
const last = cues[cues.length - 1];
const outroStart = last.t + (Number(draft.tailMs) || 0);
const endAt = outroStart + (outro === 'none' ? 0 : outMs);
const loopPause = 700;
// 和 OBS 端一致:入场 + 回缩必须塞进「到下一句」的间隔里
const fitToWindow = (index) => {
const cue = cues[index];
if (!cue) return { enterMs: baseEnterMs, shrinkMs: baseShrinkMs, windowMs: 0 };
const next = cues[index + 1];
const windowMs = Math.max(0, (next ? next.t : cue.t + (Number(draft.tailMs) || 0)) - cue.t);
const available = Math.max(120, windowMs);
if (baseEnterMs + baseShrinkMs <= available) {
return { enterMs: baseEnterMs, shrinkMs: baseShrinkMs, windowMs };
}
const enterMs = Math.round(Math.min(baseEnterMs, available * 0.45));
const shrinkMs = Math.round(Math.max(120, Math.min(baseShrinkMs, available - enterMs)));
return { enterMs, shrinkMs, windowMs };
};
const startedAt = performance.now(); const startedAt = performance.now();
setPreviewIndex(-1); setPreviewIndex(-1);
setPreviewElapsed(0); setPreviewElapsed(0);
setPreviewPhase(null);
const timer = setInterval(() => { const timer = setInterval(() => {
const elapsed = performance.now() - startedAt; const elapsed = performance.now() - startedAt;
let index = -1; let index = -1;
@@ -1033,12 +1154,28 @@
} }
setPreviewIndex(index); setPreviewIndex(index);
setPreviewElapsed(elapsed); setPreviewElapsed(elapsed);
const last = cues[cues.length - 1]; // 注意:预览用粗粒度 tick 判断阶段,字幕点到点之间可能只差 300ms,
if (elapsed > last.t + (draft.tailMs || 0) + 600) setPreviewPlaying(false); // 所以用「距本句开始已过多久」而不是绝对时间,确保每句都会走完入场→回缩。
if (index >= 0 && elapsed >= outroStart) {
setPreviewPhase(outro === 'none' ? null : 'leaving');
} else if (index >= 0) {
const fitted = fitToWindow(index);
setPreviewPhase(elapsed >= cues[index].t + fitted.enterMs ? 'hold' : 'entering');
} else {
setPreviewPhase(null);
}
if (elapsed > endAt + loopPause) {
if (previewLoop) {
setPreviewRun(v => v + 1);
} else {
setPreviewPlaying(false);
setPreviewPhase(null);
}
}
}, 50); }, 50);
return () => clearInterval(timer); return () => clearInterval(timer);
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [previewPlaying, previewRun, parsed]); }, [previewPlaying, previewRun, parsed, previewLoop]);
React.useEffect(() => { React.useEffect(() => {
if (!lrcState || !lrcState.playing) return undefined; if (!lrcState || !lrcState.playing) return undefined;
@@ -1084,11 +1221,31 @@
const stageCue = previewCue || cues[0] || null; const stageCue = previewCue || cues[0] || null;
const stageIndex = previewCue ? previewIndex : 0; const stageIndex = previewCue ? previewIndex : 0;
const stageElapsed = previewPlaying ? previewElapsed : Infinity; const stageElapsed = previewPlaying ? previewElapsed : Infinity;
// 未播放时直接展示「入场结束后的停留状态」,方便看清最终样式
const stagePhase = previewPlaying ? previewPhase : 'hold';
const sampleText = stageCue ? stageCue.text : ''; const sampleText = stageCue ? stageCue.text : '';
const sampleNext = cues[stageIndex + 1] ? cues[stageIndex + 1].text : ''; const sampleNext = cues[stageIndex + 1] ? cues[stageIndex + 1].text : '';
const selectedCount = cues.length; const selectedCount = cues.length;
const karaokeCount = cues.filter(cue => Array.isArray(cue.segments) && cue.segments.length >= 2).length; const karaokeCount = cues.filter(cue => Array.isArray(cue.segments) && cue.segments.length >= 2).length;
// 当前舞台这句的适配时长(与 OBS 端一致:入场+回缩塞进到下一句的间隔里)
const stageFitted = (() => {
const cue = stageCue;
const style = (draft && draft.style) || {};
const base = {
enterMs: Math.max(0, Number(style.enterDurationMs) || 0),
shrinkMs: Math.max(0, Number(style.shrinkDurationMs) || 0)
};
if (!cue) return base;
const next = cues[stageIndex + 1];
const windowMs = Math.max(0, (next ? next.t : cue.t + (Number(draft.tailMs) || 0)) - cue.t);
const available = Math.max(120, windowMs);
if (base.enterMs + base.shrinkMs <= available) return { ...base, windowMs };
const enterMs = Math.round(Math.min(base.enterMs, available * 0.45));
const shrinkMs = Math.round(Math.max(120, Math.min(base.shrinkMs, available - enterMs)));
return { enterMs, shrinkMs, windowMs };
})();
const saveDraft = async (options = {}) => { const saveDraft = async (options = {}) => {
if (!draft) return null; if (!draft) return null;
setSaving(true); setSaving(true);
@@ -1604,8 +1761,11 @@
nextText={sampleNext} nextText={sampleNext}
playing={previewPlaying} playing={previewPlaying}
elapsed={stageElapsed} elapsed={stageElapsed}
phase={stagePhase}
configKey={configKey}
fittedTiming={stageFitted}
/> />
<Space style={{ marginTop: 8 }}> <Space style={{ marginTop: 8 }} wrap>
<Button <Button
type="primary" type="primary"
ghost ghost
@@ -1613,8 +1773,16 @@
onClick={() => { setPreviewRun(v => v + 1); setPreviewPlaying(true); }} onClick={() => { setPreviewRun(v => v + 1); setPreviewPlaying(true); }}
>▶ 试播本段</Button> >▶ 试播本段</Button>
<Button disabled={!previewPlaying} onClick={() => setPreviewPlaying(false)}>停止试播</Button> <Button disabled={!previewPlaying} onClick={() => setPreviewPlaying(false)}>停止试播</Button>
<Space size={4}>
<Switch size="small" checked={previewLoop} onChange={setPreviewLoop} />
<Text style={{ color: '#888', fontSize: 12 }}>循环</Text>
</Space>
<Text style={{ color: '#888', fontSize: 12 }}> <Text style={{ color: '#888', fontSize: 12 }}>
{previewCue ? formatMs(previewCue.t) : '—'} / {formatMs(parsed ? parsed.totalMs : 0)} {previewCue ? formatMs(previewCue.t) : '—'} / {formatMs(parsed ? parsed.totalMs : 0)}
{previewPlaying && previewPhase ? ' · ' + (
previewPhase === 'entering' ? '入场中'
: previewPhase === 'hold' ? '停留 / 回缩' : '出场中'
) : ''}
</Text> </Text>
</Space> </Space>
</Col> </Col>
+177 -20
View File
@@ -298,8 +298,13 @@
shownIndex: -2, shownIndex: -2,
tickTimer: null, tickTimer: null,
spans: null, spans: null,
cue: null,
phase: null,
phaseTimer: null,
}; };
const LRC_OUTROS = ['none', 'fade', 'blur', 'slideDown', 'slideUp', 'zoom', 'custom'];
let lrcCustomStyleEl = null; let lrcCustomStyleEl = null;
function applyLrcCustomCss(css) { function applyLrcCustomCss(css) {
@@ -331,12 +336,60 @@
return Date.now() + clockSkewMs; return Date.now() + clockSkewMs;
} }
function getLrcTiming(style) {
const s = style || {};
const clamp = (value, min, max, fallback) => {
const n = Number(value);
return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : fallback;
};
return {
inMs: clamp(s.enterDurationMs, 0, 10000, 300),
holdMs: clamp(s.holdDurationMs, 0, 10000, 0),
outMs: clamp(s.outDurationMs, 0, 10000, 260),
shrinkMs: clamp(s.shrinkDurationMs, 0, 20000, 0),
shrinkTo: clamp(s.holdShrinkTo, 0.3, 1, 1),
blurPx: clamp(s.blurPx, 0, 60, 10),
outro: LRC_OUTROS.includes(s.outro) ? s.outro : 'fade',
};
}
/**
* 每句字幕的可用时长 = 到下一句的距离(最后一句用 tailMs)。
* 入场和回缩都必须在下一句出现前完成,否则观众看到的永远是「没缩完就跳走」。
*/
function cueWindowMs(index) {
const cue = lrc.cues[index];
if (!cue) return 0;
const next = lrc.cues[index + 1];
const end = next ? next.t : cue.t + (Number(lrc.tailMs) || 0);
return Math.max(0, end - cue.t);
}
function fitTimingToWindow(timing, windowMs) {
// 至少给回缩留 40% 的时间,否则回缩没有观感
const available = Math.max(120, windowMs || 0);
let inMs = timing.inMs;
let shrinkMs = timing.shrinkMs;
const total = inMs + shrinkMs;
if (total <= available) return { inMs, shrinkMs, fitted: false };
const inFloor = Math.min(inMs, available * 0.45);
inMs = Math.round(inFloor);
shrinkMs = Math.round(Math.max(120, Math.min(shrinkMs, available - inMs)));
return { inMs, shrinkMs, fitted: true };
}
function applyLrcStyle(style) { function applyLrcStyle(style) {
const s = style || {}; const s = style || {};
lrcLayer.className = 'lrc-layer'; lrcLayer.className = 'lrc-layer';
lrcLayer.classList.add('pos-' + (s.position || 'bottom')); lrcLayer.classList.add('pos-' + (s.position || 'bottom'));
lrcLayer.classList.add('lrc-align-' + (s.align || 'center')); lrcLayer.classList.add('lrc-align-' + (s.align || 'center'));
lrcLayer.classList.add('lrc-anim-' + (s.animation || 'fade')); lrcLayer.classList.add('lrc-anim-' + (s.animation || 'fade'));
const timing = getLrcTiming(s);
lrcLayer.classList.add('lrc-out-' + timing.outro);
lrcLayer.style.setProperty('--lrc-in-dur', timing.inMs + 'ms');
lrcLayer.style.setProperty('--lrc-out-dur', timing.outMs + 'ms');
lrcLayer.style.setProperty('--lrc-shrink-dur', timing.shrinkMs + 'ms');
lrcLayer.style.setProperty('--lrc-shrink-to', String(timing.shrinkTo)); lrcLayer.style.setProperty('--lrc-blur-px', timing.blurPx + 'px');
lrcLayer.style.paddingBottom = '0px'; lrcLayer.style.paddingBottom = '0px';
lrcLayer.style.paddingTop = '0px'; lrcLayer.style.paddingTop = '0px';
@@ -373,6 +426,9 @@
lrcNext.style.textShadow = shadow; lrcNext.style.textShadow = shadow;
lrcNext.style.display = s.showNextLine === false ? 'none' : ''; lrcNext.style.display = s.showNextLine === false ? 'none' : '';
// 下一句和当前句同属 .lrc-text 的兄弟节点,回缩时一起缩放更自然
lrcNext.style.transformOrigin = 'center';
applyLrcCustomCss(s.customCss || ''); applyLrcCustomCss(s.customCss || '');
} }
@@ -403,6 +459,90 @@
lrcLayer.classList.add('visible'); lrcLayer.classList.add('visible');
} }
// ── 入场 / 停留回缩 / 出场 状态机 ──────────────────────────
function setPhase(phase) {
if (lrc.phase === phase) return;
lrc.phase = phase;
lrcLayer.classList.remove('lrc-state-entering', 'lrc-state-hold', 'lrc-state-leaving');
if (phase) lrcLayer.classList.add('lrc-state-' + phase);
}
function clearPhaseTimer() {
if (lrc.phaseTimer) {
clearTimeout(lrc.phaseTimer);
lrc.phaseTimer = null;
}
}
function restartEntrance(cue, index) {
clearPhaseTimer();
// 关键:先把上一句残留的 hold 状态去掉并让浏览器结算掉旧的回缩过渡,
// 否则新一句会从上一次的缩小值继续,看起来像「回缩瞬间完成」或「根本不动」。
lrcLayer.classList.remove('lrc-state-entering', 'lrc-state-hold', 'lrc-state-leaving');
lrc.phase = null;
lrcText.style.transition = 'none';
lrcText.style.transform = 'scale(1)';
void lrcText.offsetWidth; // 强制重排,让上面的重置立即生效
lrcText.style.transition = '';
lrcText.style.transform = '';
// 入场 + 回缩必须塞进「到下一句的时间」里,否则回缩永远播不完
const timing = getLrcTiming(lrc.style);
const fitted = fitTimingToWindow(timing, cueWindowMs(index));
lrcLayer.style.setProperty('--lrc-in-dur', fitted.inMs + 'ms');
lrcLayer.style.setProperty('--lrc-shrink-dur', fitted.shrinkMs + 'ms');
setPhase('entering');
showLrc();
const current = cue;
lrc.phaseTimer = setTimeout(() => {
lrc.phaseTimer = null;
if (!lrc.active || lrc.cue !== current) return;
// 入场结束 -> 停留阶段(从 1 开始缓慢回缩)
setPhase('hold');
}, fitted.inMs + timing.holdMs + 20);
return fitted;
}
function beginOutro(onDone) {
clearPhaseTimer();
const timing = getLrcTiming(lrc.style);
lrc.cue = null;
if (timing.outro === 'none' || timing.outMs <= 0) {
lrcLayer.classList.remove('lrc-state-entering', 'lrc-state-hold', 'lrc-state-leaving');
lrc.phase = null;
hideLrc();
onDone();
return;
}
// 出场动画要作用在「当前可见的尺寸」上,先把回缩的 transform 固定住再切到 leaving
const computed = getComputedStyle(lrcText).transform;
lrcLayer.classList.remove('lrc-state-entering', 'lrc-state-hold', 'lrc-state-leaving');
lrc.phase = null;
lrcText.style.transition = 'none';
if (computed && computed !== 'none') lrcText.style.transform = computed;
void lrcText.offsetWidth;
lrcText.style.transition = '';
lrcText.style.transform = '';
setPhase('leaving');
lrc.phaseTimer = setTimeout(() => {
lrc.phaseTimer = null;
setPhase(null);
hideLrc();
if (onDone) onDone();
}, timing.outMs + 20);
}
function clearLrcContent() {
lrc.cue = null;
lrc.spans = null;
lrcText.textContent = '';
lrcNext.textContent = '';
}
function cueUsesKaraoke(cue) { function cueUsesKaraoke(cue) {
return !!(lrc.style && lrc.style.karaoke !== false && cue return !!(lrc.style && lrc.style.karaoke !== false && cue
&& Array.isArray(cue.segments) && cue.segments.length >= 2); && Array.isArray(cue.segments) && cue.segments.length >= 2);
@@ -439,16 +579,28 @@
function renderCue(index) { function renderCue(index) {
if (index === lrc.shownIndex) return; if (index === lrc.shownIndex) return;
lrc.shownIndex = index;
if (index < 0) { if (index < 0) {
// 还没到第一句:只有本次播放尚未入场过时才清空,避免打断正在进行的出场动画
const neverShown = lrc.shownIndex === -2;
lrc.shownIndex = -2;
if (neverShown) {
if (lrc.spans) {
lrc.spans = null;
lrcText.textContent = '';
lrcNext.textContent = '';
}
} else if (lrc.cue) {
lrc.cue = null;
lrc.spans = null;
lrcText.textContent = '';
lrcNext.textContent = '';
}
hideLrc(); hideLrc();
lrc.spans = null;
lrcText.textContent = '';
lrcNext.textContent = '';
return; return;
} }
lrc.shownIndex = index;
const cue = lrc.cues[index]; const cue = lrc.cues[index];
if (!cue) { if (!cue) {
hideLrc(); hideLrc();
@@ -466,11 +618,9 @@
// 逐字模式下下一句也可能带增强标签,这里统一只显示纯文本 // 逐字模式下下一句也可能带增强标签,这里统一只显示纯文本
lrcNext.textContent = next ? next.text : ''; lrcNext.textContent = next ? next.text : '';
// 重启入场动画 lrc.cue = cue;
lrcText.style.animation = 'none'; lrc.cueIndex = index;
void lrcText.offsetWidth; restartEntrance(cue, index);
lrcText.style.animation = '';
showLrc();
} }
function currentElapsed() { function currentElapsed() {
@@ -483,7 +633,8 @@
const elapsed = currentElapsed(); const elapsed = currentElapsed();
const last = lrc.cues[lrc.cues.length - 1]; const last = lrc.cues[lrc.cues.length - 1];
if (last && elapsed > last.t + lrc.tailMs) { if (last && elapsed > last.t + lrc.tailMs) {
hideLrc(); // 整段结束:播放淡出/出场动画
if (lrc.cue) beginOutro();
return; return;
} }
renderCue(findCueIndex(elapsed)); renderCue(findCueIndex(elapsed));
@@ -505,19 +656,25 @@
function applyLrcState(state) { function applyLrcState(state) {
if (!state || !state.playing) { if (!state || !state.playing) {
const reason = state && state.reason; const reason = state && state.reason;
const wasActive = lrc.active;
lrc.active = false; lrc.active = false;
stopTicker(); stopTicker();
hideLrc(); if (!wasActive) {
lrc.shownIndex = -2; // 其他客户端已经播完并淡出,这里直接收尾
if (reason === 'stopped' || reason === 'ended' || reason === 'cleared' || reason === 'preset-deleted') { clearPhaseTimer();
setTimeout(() => { setPhase(null);
if (!lrc.active) { hideLrc();
lrc.spans = null; clearLrcContent();
lrcText.textContent = ''; lrc.shownIndex = -2;
lrcNext.textContent = ''; return;
}
}, 240);
} }
if (lrc.cue) {
// 播放被停止/清空:走一遍出场动画再清空
beginOutro(clearLrcContent);
} else {
clearLrcContent();
}
lrc.shownIndex = -2;
return; return;
} }
+42
View File
@@ -224,3 +224,45 @@ test('normalizeStyle 支持禁用背景 / 阴影 / 逐字', () => {
assert.equal(defaults.style.textShadowEnabled, true); assert.equal(defaults.style.textShadowEnabled, true);
assert.equal(defaults.style.karaoke, true); assert.equal(defaults.style.karaoke, true);
}); });
test('normalizeStyle 支持入场时长 / 出场 / 回缩参数', () => {
const preset = normalizeLrcPreset({
id: 'durations',
source: '[00:01.00]A',
style: {
animation: 'blur',
enterDurationMs: 1500,
outro: 'blur',
outDurationMs: 800,
holdShrinkTo: 0.94,
shrinkDurationMs: 2500,
blurPx: 24,
},
});
assert.equal(preset.style.animation, 'blur');
assert.equal(preset.style.enterDurationMs, 1500);
assert.equal(preset.style.outro, 'blur');
assert.equal(preset.style.outDurationMs, 800);
assert.equal(preset.style.holdShrinkTo, 0.94);
assert.equal(preset.style.shrinkDurationMs, 2500);
assert.equal(preset.style.blurPx, 24);
// 超界值被收敛
const clamped = normalizeLrcPreset({
id: 'clamped',
source: '',
style: { enterDurationMs: -100, outDurationMs: 999999, holdShrinkTo: 5, shrinkDurationMs: -1, blurPx: 900 },
});
assert.equal(clamped.style.enterDurationMs, 0);
assert.equal(clamped.style.outDurationMs, 10000);
assert.equal(clamped.style.holdShrinkTo, 1);
assert.equal(clamped.style.shrinkDurationMs, 0);
assert.equal(clamped.style.blurPx, 60);
// 非法枚举回退默认
const fallback = normalizeLrcPreset({ id: 'fallback', source: '', style: { outro: 'spin' } });
assert.equal(fallback.style.outro, 'fade');
assert.equal(fallback.style.enterDurationMs, 300);
assert.equal(fallback.style.outDurationMs, 260);
assert.equal(fallback.style.holdShrinkTo, 1);
});