Initial AI video editor prototype

This commit is contained in:
haixin.yang committed 2026-07-09 12:48:04 +08:00
commit d356816dda
22 files changed
+12866

No files matched your search

+38
View File
@@ -0,0 +1,38 @@
# dependencies
node_modules/
# build output
dist/
# local QA captures and generated media
qa/
design-qa.md
AGENTS.md
# local package/cache files
.npm-cache/
.npmrc
.netlify/
.vite/
.vite-temp/
# logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# local environment
.env
.env.*
!.env.example
# OS/editor noise
.DS_Store
Thumbs.db
.idea/
.vscode/
# Local Netlify folder
.netlify
+185
View File
@@ -0,0 +1,185 @@
# ai-video-editor
A browser-first AI video editor for image/video timelines, AI voiceover generation, captions, background music, and MP4/WebM export. The current prototype is inspired by modern dark timeline editors such as CapCut, but focuses on fully client-side AI voiceover workflows.
中文简介:这是一个 Web 端 AI 视频编辑器原型,支持本地上传图片/视频/音频、时间轴剪辑、字幕、AI 配音、背景音乐、多语言界面和浏览器内导出。
## Live Demo
- Production: https://web-player-ai-voice-editor.netlify.app
## What It Can Do
- Upload local images, videos, and audio files.
- Drag assets from the media library into timeline tracks.
- Arrange and resize visual clips on the image/video track.
- Preview a project even before generating voiceover audio.
- Generate AI voiceover from typed scripts.
- Align generated audio, captions, and visual clips on the timeline.
- Edit captions by dragging, hiding, deleting, and changing placement/size.
- Add video source audio and separate it onto its own track.
- Add background music on a dedicated music track.
- Use multi-track timeline controls: visibility, lock, delete, duplicate, split, zoom, snap, and reorder.
- Apply filters, effects, stickers, and transition presets.
- Export MP4 when browser support is available, with WebM fallback.
- Show export progress during local rendering.
- Persist language selection in `localStorage`.
## AI Features
Current AI capabilities are designed to run in the browser as much as possible:
- Text-to-speech with ONNX/browser engines.
- Chinese voiceover via Piper/VITS browser ONNX models.
- English voice options via Kokoro 82M ONNX.
- Lightweight voice preview and history restore.
- Script-to-caption timeline alignment based on generated audio duration.
- Browser voice recording for manually captured narration.
- Local waveform decoding for voiceover, source audio, and background music.
## Multilingual UI
The editor includes a first-run language picker and stores the chosen language locally.
Currently included languages:
- Chinese
- English
- Japanese
- Korean
- Spanish
- French
- German
- Portuguese
- Thai
- Vietnamese
The language picker includes English guidance so non-Chinese users can understand the first screen.
## Future AI Roadmap
Planned or desirable AI capabilities:
- Automatic speech recognition for uploaded videos and recorded narration.
- Auto subtitle generation and subtitle translation.
- AI script writing and rewrite modes for marketing, education, short video, and product demos.
- Voice cloning or custom speaker adaptation, with clear consent and privacy controls.
- Multi-speaker dubbing and role-based dialogue generation.
- Smart alignment between narration, captions, images, and visual beats.
- AI scene detection for uploaded videos.
- Automatic highlight extraction from long videos.
- AI background music recommendation and beat matching.
- Noise reduction, loudness normalization, and vocal enhancement.
- AI image/video enhancement, background removal, and object segmentation.
- Cloud-assisted model loading for larger models while keeping an offline/local-first mode.
- Batch export and template-based video generation.
## Tech Stack
- React 19
- Vite 6
- ONNX/browser TTS dependencies
- `@ffmpeg/ffmpeg` for browser-side media processing support
- Browser MediaRecorder/export pipeline
- Phosphor Icons
- Netlify deployment
## Project Structure
```text
src/
App.jsx
components/
PreviewStage.jsx
Timeline.jsx
Topbar.jsx
VoicePanel.jsx
panels.jsx
ui.jsx
config/
editor.js
lib/
media.js
timeline.js
i18n.js
main.jsx
styles.css
public/
assets/
netlify.toml
```
## Local Development
```bash
npm install
npm run dev
```
Build for production:
```bash
npm run build
```
Preview the production build:
```bash
npm run preview
```
## Deployment
This project is configured for Netlify:
```bash
npm run build
npx netlify-cli deploy --prod --dir=dist
```
`netlify.toml` defines:
- build command: `npm run build`
- publish directory: `dist`
- SPA fallback redirect to `index.html`
## Repository Hygiene
The following are intentionally excluded from git:
- `node_modules/`
- `dist/`
- `qa/`
- local downloads, screenshots, and generated QA media
- `.netlify/`
- local npm cache and machine-specific config
- local Codex/agent notes
## 中文说明
### 当前能力
- 本地上传图片、视频、音频素材。
- 素材库九宫格展示,并支持拖拽到对应轨道。
- 图片/视频轨道支持多片段、拖拽排序、缩放时长、删除和切分。
- 配音轨、视频原声轨、背景音乐轨独立管理。
- 无需先生成配音,也可以播放图片/视频时间线预览。
- AI 配音支持中文 Piper/VITS ONNX 和英文 Kokoro ONNX 方向。
- 字幕可编辑、可拖动、可隐藏、可删除,并随音频时长对齐。
- 支持多语言首屏选择,并自动保存到本地。
- 支持浏览器端 MP4/WebM 导出,并显示导出进度。
### 后续 AI 方向
- 自动识别视频语音并生成字幕。
- 字幕翻译和多语言配音。
- AI 文案生成、改写、风格化。
- 声音克隆和多角色配音。
- 根据语音自动对齐图片、字幕和节奏点。
- 视频场景检测、长视频高光提取。
- 背景音乐推荐、节拍匹配、音频增强。
- 图片/视频画质增强、抠图、主体分割。
## License
Prototype project. Add a license before public production use.
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href="data:," />
<title>AI Voiceover Studio</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
+8
View File
@@ -0,0 +1,8 @@
[build]
command = "npm run build"
publish = "dist"
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
+2797
View File
File diff suppressed because it is too large. Load diff
+22
View File
@@ -0,0 +1,22 @@
{
"name": "web-player",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --host 127.0.0.1",
"build": "vite build",
"preview": "vite preview --host 127.0.0.1"
},
"dependencies": {
"@diffusionstudio/vits-web": "^1.0.3",
"@ffmpeg/ffmpeg": "^0.12.15",
"@ffmpeg/util": "^0.12.2",
"@phosphor-icons/react": "^2.1.10",
"@vitejs/plugin-react": "5.0.4",
"kokoro-js": "^1.2.1",
"react": "19.2.0",
"react-dom": "19.2.0",
"vite": "6.4.2"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

+3127
View File
File diff suppressed because it is too large. Load diff
+184
View File
@@ -0,0 +1,184 @@
import {
CaretDown,
CloudArrowUp,
FrameCorners,
Pause,
Play,
SkipBack,
SkipForward,
} from "@phosphor-icons/react";
import { formatTime } from "../lib/timeline.js";
import { IconButton } from "./ui.jsx";
export function PreviewStage({
t,
previewShellRef,
previewCanvasRef,
previewVideoRef,
previewVisualSrc,
previewVisualType,
previewRatio,
previewFrameStyle,
trackVisibility,
fileInputRef,
selectedFilter,
fitMode,
setFitMode,
audioUrl,
setIsPlaying,
setCurrentTime,
captionsEnabled,
currentCaption,
captionSize,
captionPlacement,
startCaptionDrag,
setActiveTool,
selectedSticker,
isPlaying,
canPreview,
handlePlayToggle,
estimatedDuration,
currentTime,
seekTo,
notify,
}) {
return (
<section className="preview-stage">
<div
ref={previewShellRef}
className={`preview-canvas fit-${fitMode} ${previewVisualSrc ? "" : "is-empty"} ${
previewVisualSrc && !trackVisibility.image ? "is-image-hidden" : ""
}`}
style={{ "--preview-ratio": previewRatio }}
>
{!previewVisualSrc ? (
<button className="preview-empty" type="button" style={previewFrameStyle} onClick={() => fileInputRef.current?.click()}>
<CloudArrowUp size={38} />
<strong>{t("previewEmptyTitle")}</strong>
<span>{t("previewEmptySubtitle")}</span>
</button>
) : (
<div
ref={previewCanvasRef}
className={`preview-frame ${previewVisualSrc && !trackVisibility.image ? "is-image-hidden" : ""}`}
data-hidden-label={t("imageHidden")}
style={previewFrameStyle}
>
{trackVisibility.image && previewVisualType === "image" ? (
<img
src={previewVisualSrc}
alt={t("currentMediaAlt")}
style={{
filter: selectedFilter.css,
objectFit: fitMode,
}}
/>
) : null}
{trackVisibility.image && previewVisualType === "video" ? (
<video
key={previewVisualSrc}
ref={previewVideoRef}
className="preview-video"
src={previewVisualSrc}
muted
playsInline
preload="metadata"
style={{
filter: selectedFilter.css,
objectFit: fitMode,
}}
onPlay={() => {
if (!audioUrl) {
setIsPlaying(true);
}
}}
onPause={() => {
if (!audioUrl) {
setIsPlaying(false);
}
}}
onEnded={() => {
setIsPlaying(false);
setCurrentTime(0);
}}
onTimeUpdate={(event) => {
if (!audioUrl) {
setCurrentTime(event.currentTarget.currentTime);
}
}}
/>
) : null}
{captionsEnabled && trackVisibility.caption && currentCaption ? (
<button
className="caption-overlay"
type="button"
style={{
fontSize: captionSize,
left: `${captionPlacement.x}%`,
top: `${captionPlacement.y}%`,
}}
onPointerDown={startCaptionDrag}
onDoubleClick={() => setActiveTool("caption")}
>
{currentCaption}
</button>
) : null}
{selectedSticker.text ? <div className="sticker-overlay">{selectedSticker.text}</div> : null}
<button
className={`canvas-play-button ${isPlaying ? "is-playing" : ""}`}
type="button"
aria-label={isPlaying ? t("pause") : t("play")}
title={isPlaying ? t("pause") : t("play")}
disabled={!canPreview}
onClick={handlePlayToggle}
>
{isPlaying ? <Pause size={18} weight="fill" /> : <Play size={18} weight="fill" />}
<span>{isPlaying ? t("pause") : t("play")}</span>
</button>
</div>
)}
</div>
<div className="transport">
<input
className="scrubber"
type="range"
min="0"
max={Math.max(estimatedDuration, 1)}
step="0.01"
value={Math.min(currentTime, estimatedDuration)}
onChange={(event) => seekTo(Number(event.target.value))}
/>
<div className="transport-row">
<span>
{formatTime(currentTime)} <em>/ {formatTime(estimatedDuration)}</em>
</span>
<div className="playback-controls">
<IconButton label={t("backTwoSeconds")} onClick={() => seekTo(currentTime - 2)}>
<SkipBack size={18} weight="fill" />
</IconButton>
<IconButton label={t("play")} active onClick={handlePlayToggle}>
{isPlaying ? <Pause size={20} weight="fill" /> : <Play size={20} weight="fill" />}
</IconButton>
<IconButton label={t("forwardTwoSeconds")} onClick={() => seekTo(currentTime + 2)}>
<SkipForward size={18} weight="fill" />
</IconButton>
</div>
<button
className="fit-button"
type="button"
onClick={() => {
setFitMode((mode) => (mode === "contain" ? "cover" : "contain"));
notify(fitMode === "contain" ? "预览已切换为填充裁切" : "预览已切换为完整适配");
}}
>
{fitMode === "contain" ? t("fit") : t("cover")} <CaretDown size={14} />
</button>
<IconButton label={t("fullscreenPreview")} onClick={() => document.documentElement.requestFullscreen?.()}>
<FrameCorners size={19} />
</IconButton>
</div>
</div>
</section>
);
}
+528
View File
@@ -0,0 +1,528 @@
import {
ArrowClockwise,
ArrowCounterClockwise,
ArrowsInLineHorizontal,
ArrowsOutLineHorizontal,
CopySimple,
Crop,
Eye,
EyeSlash,
LockKey,
LockKeyOpen,
MagnifyingGlassMinus,
MagnifyingGlassPlus,
MinusCircle,
MonitorPlay,
Pause,
Play,
PlusCircle,
Scissors,
Trash,
} from "@phosphor-icons/react";
import { IMAGE_SEGMENT_SECONDS } from "../config/editor.js";
import { formatClock, formatTime, getImageThumbnailCount, getSegmentStartTime } from "../lib/timeline.js";
import { IconButton, WaveformStrip } from "./ui.jsx";
export function Timeline({
t,
undo,
redo,
handleDeleteTrack,
handleDuplicateTrack,
handleCutTrack,
fitMode,
setFitMode,
canPreview,
handlePlayToggle,
isPlaying,
handleAddSegment,
handleRemoveSegment,
adjustSelectedSegmentWeight,
timelineZoom,
setTimelineZoom,
selectedTrack,
setSelectedTrack,
trackVisibility,
toggleTrackVisibility,
trackLocks,
toggleTrackLock,
trackScrollRef,
trackWidth,
startTimelineSeek,
timelineDuration,
currentTime,
playheadPercent,
snapGuide,
assetDropTargetTrack,
assetDropPosition,
assetDropPulseTrack,
assetDragPreview,
handleTrackAssetDragOver,
handleTrackAssetDragLeave,
handleTrackAssetDrop,
activeTimelineClipDrag,
imageSrc,
displayedVisualSegments,
renderedVisualTimeline,
visualType,
currentVisualSegment,
selectedVisualSegmentId,
currentVisualSegmentIndex,
setSelectedVisualSegmentId,
seekTo,
suppressTimelineClipClickRef,
startTimelineClipDrag,
startImageResize,
displayedCaptionSegments,
displayedCaptionTimeline,
currentCaptionSegment,
selectedSegmentId,
setSelectedSegmentId,
captionTargetDuration,
sourceAudioBlob,
sourceAudioPeaks,
sourceAudioClipPercent,
sourceAudioDuration,
audioBlob,
peaks,
audioClipPercent,
audioDuration,
musicBlob,
musicPeaks,
musicClipPercent,
musicDuration,
}) {
const draggingVisualSegment =
activeTimelineClipDrag?.track === "image"
? displayedVisualSegments.find((segment) => segment.id === activeTimelineClipDrag.segmentId)
: null;
const draggingCaptionSegment =
activeTimelineClipDrag?.track === "caption"
? displayedCaptionSegments.find((segment) => segment.id === activeTimelineClipDrag.segmentId)
: null;
const renderAssetDropSlot = (track) =>
assetDropTargetTrack === track ? (
<div
className={`asset-drop-slot type-${assetDragPreview?.type || "asset"} ${
assetDragPreview?.src ? "has-thumb" : ""
}`}
style={{ "--drop-x": `${assetDropPosition?.track === track ? assetDropPosition.percent : 50}%` }}
>
{assetDragPreview?.src ? (
<div className="asset-drop-slot-thumb">
{assetDragPreview.type === "video" ? (
<video src={assetDragPreview.src} muted playsInline preload="metadata" draggable={false} />
) : assetDragPreview.type === "audio" ? (
<span>{t("assetAudio")}</span>
) : (
<img src={assetDragPreview.src} alt="" draggable={false} />
)}
</div>
) : null}
<span>{t("dropSlot", "释放到这里")}</span>
<strong>
{assetDragPreview?.type === "audio"
? t("assetAudio")
: assetDragPreview?.type === "video"
? t("assetVideo")
: t("assetImage")}
</strong>
</div>
) : null;
return (
<section className="timeline">
<div className="timeline-tools">
<div className="timeline-icon-group">
<IconButton label={t("undo")} onClick={undo}>
<ArrowCounterClockwise size={17} />
</IconButton>
<IconButton label={t("redo")} onClick={redo}>
<ArrowClockwise size={17} />
</IconButton>
<IconButton label={t("deleteTrack")} onClick={handleDeleteTrack}>
<Trash size={17} />
</IconButton>
<IconButton label={t("duplicateTrack")} onClick={handleDuplicateTrack}>
<CopySimple size={17} />
</IconButton>
<IconButton label={t("cutSegment")} onClick={handleCutTrack}>
<Scissors size={17} />
</IconButton>
<IconButton
label={t("cropCanvas")}
active={fitMode === "cover"}
onClick={() => setFitMode((mode) => (mode === "cover" ? "contain" : "cover"))}
>
<Crop size={17} />
</IconButton>
</div>
<div className="timeline-segment-tools">
<button className="timeline-play-button" type="button" disabled={!canPreview} onClick={handlePlayToggle}>
{isPlaying ? <Pause size={17} weight="fill" /> : <Play size={17} weight="fill" />}
{isPlaying ? t("pause") : t("play")}
</button>
<button type="button" onClick={handleAddSegment}>
<PlusCircle size={17} />
{t("addSegment")}
</button>
<button type="button" onClick={handleRemoveSegment}>
<MinusCircle size={17} />
{t("removeSegment")}
</button>
<IconButton label={t("shortenSegment")} onClick={() => adjustSelectedSegmentWeight(-0.5)}>
<ArrowsInLineHorizontal size={18} />
</IconButton>
<IconButton label={t("lengthenSegment")} onClick={() => adjustSelectedSegmentWeight(0.5)}>
<ArrowsOutLineHorizontal size={18} />
</IconButton>
</div>
<div className="timeline-icon-group">
<IconButton label={t("zoomOut")} onClick={() => setTimelineZoom((zoom) => Math.max(0.25, zoom - 0.25))}>
<MagnifyingGlassMinus size={17} />
</IconButton>
<span className="zoom-readout">{Math.round(timelineZoom * 100)}%</span>
<IconButton label={t("fitTimeline")} active={timelineZoom === 1} onClick={() => setTimelineZoom(1)}>
<MonitorPlay size={17} />
</IconButton>
<IconButton label={t("zoomIn")} onClick={() => setTimelineZoom((zoom) => Math.min(3, zoom + 0.25))}>
<MagnifyingGlassPlus size={17} />
</IconButton>
</div>
</div>
<div className="timeline-board">
<div className="track-labels">
{[
["image", t("imageTrack")],
["caption", t("caption")],
["source", t("sourceTrack")],
["audio", t("voiceTrack")],
["music", t("musicTrack")],
].map(([track, label]) => (
<div className={selectedTrack === track ? "is-selected" : ""} key={track}>
<button
type="button"
aria-label={`${label} ${t("visible")}`}
onClick={(event) => {
event.stopPropagation();
toggleTrackVisibility(track);
}}
>
{trackVisibility[track] ? <Eye size={15} /> : <EyeSlash size={15} />}
</button>
<button
type="button"
aria-label={`${label} ${t("lock")}`}
onClick={(event) => {
event.stopPropagation();
toggleTrackLock(track);
}}
>
{trackLocks[track] ? <LockKey size={15} /> : <LockKeyOpen size={15} />}
</button>
<button className="track-name-button" type="button" onClick={() => setSelectedTrack(track)}>
{label}
</button>
</div>
))}
</div>
<div className="tracks">
<div
ref={trackScrollRef}
className="track-scroll"
style={{ width: trackWidth, "--timeline-zoom": timelineZoom }}
onPointerDown={(event) => {
if (
event.target.closest(
"button, .image-clip, .caption-segment, .audio-track, .waveform-strip",
)
) {
return;
}
startTimelineSeek(event);
}}
>
<div className="ruler" onPointerDown={startTimelineSeek}>
{Array.from({ length: 11 }, (_, index) => (
<span key={index}>{formatClock((timelineDuration / 10) * index)}</span>
))}
</div>
<div
className="playhead"
role="slider"
aria-label={t("dragPlayhead")}
aria-valuemin={0}
aria-valuemax={Math.round(timelineDuration)}
aria-valuenow={Math.round(currentTime)}
style={{ left: `${playheadPercent}%` }}
onPointerDown={startTimelineSeek}
/>
{snapGuide && timelineDuration > 0 ? (
<div
className="snap-guide"
style={{
left: `${Math.max(0, Math.min(100, (snapGuide.time / timelineDuration) * 100))}%`,
}}
>
<span>{snapGuide.label}</span>
</div>
) : null}
<div
className={`image-track ${selectedTrack === "image" ? "is-selected" : ""} ${
assetDropTargetTrack === "image" ? "is-drop-target" : ""
} ${assetDropPulseTrack === "image" ? "is-drop-landing" : ""} ${
activeTimelineClipDrag?.track === "image" ? "is-reordering" : ""
}`}
onClick={() => setSelectedTrack("image")}
onDragOver={(event) => handleTrackAssetDragOver(event, "image")}
onDragLeave={(event) => handleTrackAssetDragLeave(event, "image")}
onDrop={(event) => handleTrackAssetDrop(event, "image")}
data-asset-drop-track="image"
data-timeline-reorder-track="image"
>
{assetDropTargetTrack === "image" ? (
<div className="track-drop-hint">{t("dropVisualHere")}</div>
) : null}
{trackVisibility.image && imageSrc
? displayedVisualSegments.map((segment, index) => {
const segmentSrc = segment.src || imageSrc;
const segmentType = segment.type || visualType;
const segmentWidth =
timelineDuration > 0
? Math.max(0.8, Math.min(100, (segment.duration / timelineDuration) * 100))
: 0;
const segmentRange = renderedVisualTimeline[index];
const isCurrentVisualSegment =
segment.id === currentVisualSegment?.id ||
(currentTime >= (segmentRange?.start ?? 0) && currentTime < (segmentRange?.end ?? 0));
const isSelectedVisualSegment =
segment.id === selectedVisualSegmentId ||
(!selectedVisualSegmentId && index === currentVisualSegmentIndex);
const isDraggingVisualSegment =
activeTimelineClipDrag?.track === "image" &&
activeTimelineClipDrag.segmentId === segment.id;
const isReorderTarget =
activeTimelineClipDrag?.track === "image" &&
activeTimelineClipDrag.overIndex === index &&
!isDraggingVisualSegment;
return (
<div
key={segment.id}
role="button"
tabIndex={0}
data-timeline-segment-track="image"
data-timeline-segment-index={index}
data-timeline-segment-id={segment.id}
data-placeholder={t("dropSlot", "放置位置")}
style={{ "--image-clip-width": `${segmentWidth}%` }}
className={`image-clip ${segmentType === "video" ? "is-video" : ""} ${
isCurrentVisualSegment ? "is-current" : ""
} ${isSelectedVisualSegment ? "is-selected-segment" : ""} ${
isDraggingVisualSegment ? "is-reorder-dragging" : ""
} ${isReorderTarget ? "is-reorder-target" : ""}`}
onPointerDown={(event) => startTimelineClipDrag(event, "image", segment.id, index)}
onClick={(event) => {
event.stopPropagation();
if (suppressTimelineClipClickRef.current === segment.id) {
return;
}
setSelectedTrack("image");
setSelectedVisualSegmentId(segment.id);
seekTo(segmentRange?.start ?? 0);
}}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
setSelectedTrack("image");
setSelectedVisualSegmentId(segment.id);
seekTo(segmentRange?.start ?? 0);
}
}}
>
<div className={`image-thumbnails ${segmentType === "video" ? "is-video" : ""}`}>
{segmentType === "video" ? (
<video src={segmentSrc} muted playsInline preload="metadata" draggable={false} />
) : (
Array.from(
{
length: Math.max(
1,
getImageThumbnailCount(segment.duration || IMAGE_SEGMENT_SECONDS),
),
},
(_, thumbnailIndex) => (
<img src={segmentSrc} alt="" draggable={false} key={thumbnailIndex} />
),
)
)}
</div>
<span className="image-clip-duration">{formatClock(segment.duration)}</span>
{!activeTimelineClipDrag ? (
<button
className="image-resize-handle"
type="button"
aria-label={t("dragImageDuration")}
onPointerDown={(event) => startImageResize(event, segment.id, index)}
/>
) : null}
</div>
);
})
: null}
{renderAssetDropSlot("image")}
</div>
<div
className={`caption-track ${selectedTrack === "caption" ? "is-selected" : ""} ${
activeTimelineClipDrag?.track === "caption" ? "is-reordering" : ""
}`}
onClick={() => setSelectedTrack("caption")}
data-timeline-reorder-track="caption"
>
{trackVisibility.caption
? displayedCaptionSegments.map((segment, index) => {
const segmentDuration = displayedCaptionTimeline[index]?.duration ?? 0;
const segmentWidth =
timelineDuration > 0
? Math.max(0.6, Math.min(100, (segmentDuration / timelineDuration) * 100))
: 0;
const isDraggingCaptionSegment =
activeTimelineClipDrag?.track === "caption" &&
activeTimelineClipDrag.segmentId === segment.id;
const isReorderTarget =
activeTimelineClipDrag?.track === "caption" &&
activeTimelineClipDrag.overIndex === index &&
!isDraggingCaptionSegment;
return (
<button
type="button"
className={`caption-segment ${
segment.id === currentCaptionSegment?.id ? "is-current" : ""
} ${segment.id === selectedSegmentId ? "is-selected-segment" : ""} ${
segment.hidden ? "is-hidden" : ""
} ${isDraggingCaptionSegment ? "is-reorder-dragging" : ""} ${
isReorderTarget ? "is-reorder-target" : ""
}`}
key={segment.id}
data-timeline-segment-track="caption"
data-timeline-segment-index={index}
data-timeline-segment-id={segment.id}
data-placeholder={t("dropSlot", "放置位置")}
style={{ "--caption-width": `${segmentWidth}%` }}
onPointerDown={(event) => startTimelineClipDrag(event, "caption", segment.id, index)}
onClick={(event) => {
event.stopPropagation();
if (suppressTimelineClipClickRef.current === segment.id) {
return;
}
setSelectedTrack("caption");
setSelectedSegmentId(segment.id);
seekTo(getSegmentStartTime(displayedCaptionSegments, index, captionTargetDuration));
}}
>
{segment.text}
</button>
);
})
: null}
</div>
<button
className={`audio-track source-track ${selectedTrack === "source" ? "is-selected" : ""} ${
assetDropTargetTrack === "source" ? "is-drop-target" : ""
} ${assetDropPulseTrack === "source" ? "is-drop-landing" : ""}`}
type="button"
onClick={() => setSelectedTrack("source")}
onDragOver={(event) => handleTrackAssetDragOver(event, "source")}
onDragLeave={(event) => handleTrackAssetDragLeave(event, "source")}
onDrop={(event) => handleTrackAssetDrop(event, "source")}
data-asset-drop-track="source"
>
{assetDropTargetTrack === "source" ? (
<div className="track-drop-hint">{t("dropSourceHere")}</div>
) : null}
{renderAssetDropSlot("source")}
{trackVisibility.source && sourceAudioBlob ? (
<div className="audio-clip is-source" style={{ width: `${sourceAudioClipPercent}%` }}>
<WaveformStrip peaks={sourceAudioPeaks} active />
<span className="audio-clip-duration">{formatTime(sourceAudioDuration)}</span>
</div>
) : null}
</button>
<button
className={`audio-track ${selectedTrack === "audio" ? "is-selected" : ""} ${
assetDropTargetTrack === "audio" ? "is-drop-target" : ""
} ${assetDropPulseTrack === "audio" ? "is-drop-landing" : ""}`}
type="button"
onClick={() => setSelectedTrack("audio")}
onDragOver={(event) => handleTrackAssetDragOver(event, "audio")}
onDragLeave={(event) => handleTrackAssetDragLeave(event, "audio")}
onDrop={(event) => handleTrackAssetDrop(event, "audio")}
data-asset-drop-track="audio"
>
{assetDropTargetTrack === "audio" ? (
<div className="track-drop-hint">{t("dropVoiceHere")}</div>
) : null}
{renderAssetDropSlot("audio")}
{trackVisibility.audio && audioBlob ? (
<div className="audio-clip" style={{ width: `${audioClipPercent}%` }}>
<WaveformStrip peaks={peaks} active />
<span className="audio-clip-duration">{formatTime(audioDuration)}</span>
</div>
) : null}
</button>
<button
className={`audio-track music-track ${selectedTrack === "music" ? "is-selected" : ""} ${
assetDropTargetTrack === "music" ? "is-drop-target" : ""
} ${assetDropPulseTrack === "music" ? "is-drop-landing" : ""}`}
type="button"
onClick={() => setSelectedTrack("music")}
onDragOver={(event) => handleTrackAssetDragOver(event, "music")}
onDragLeave={(event) => handleTrackAssetDragLeave(event, "music")}
onDrop={(event) => handleTrackAssetDrop(event, "music")}
data-asset-drop-track="music"
>
{assetDropTargetTrack === "music" ? (
<div className="track-drop-hint">{t("dropMusicHere")}</div>
) : null}
{renderAssetDropSlot("music")}
{trackVisibility.music && musicBlob ? (
<div className="audio-clip is-music" style={{ width: `${musicClipPercent}%` }}>
<WaveformStrip peaks={musicPeaks} active />
<span className="audio-clip-duration">{formatTime(musicDuration)}</span>
</div>
) : null}
</button>
</div>
</div>
</div>
{draggingVisualSegment ? (
<div
className={`timeline-drag-ghost type-${draggingVisualSegment.type || visualType}`}
style={{ left: activeTimelineClipDrag.x, top: activeTimelineClipDrag.y }}
>
<div className="timeline-drag-ghost-thumb">
{(draggingVisualSegment.type || visualType) === "video" ? (
<video src={draggingVisualSegment.src || imageSrc} muted playsInline preload="metadata" draggable={false} />
) : (
<img src={draggingVisualSegment.src || imageSrc} alt="" draggable={false} />
)}
</div>
<span>{formatClock(draggingVisualSegment.duration)}</span>
</div>
) : null}
{draggingCaptionSegment ? (
<div
className="timeline-drag-ghost type-caption"
style={{ left: activeTimelineClipDrag.x, top: activeTimelineClipDrag.y }}
>
<strong>{draggingCaptionSegment.text}</strong>
</div>
) : null}
</section>
);
}
+179
View File
@@ -0,0 +1,179 @@
import {
ArrowClockwise,
ArrowCounterClockwise,
CaretDown,
FileArrowDown,
GearSix,
Pause,
Play,
ShieldCheck,
SlidersHorizontal,
} from "@phosphor-icons/react";
import { RATIO_OPTIONS } from "../config/editor.js";
import { APP_LANGUAGES, saveLanguagePreference } from "../i18n.js";
import { IconButton, Popover } from "./ui.jsx";
export function Topbar({
t,
compactRail,
setCompactRail,
lastSaved,
undo,
redo,
ratio,
ratioId,
showRatioMenu,
setShowRatioMenu,
setRatioId,
notify,
isPlaying,
handlePlayToggle,
imageSrc,
exporting,
handleExportVideo,
showSettings,
setShowSettings,
activeLanguage,
setUiLanguage,
captionsEnabled,
setCaptionsEnabled,
trackVisibility,
toggleTrackVisibility,
}) {
return (
<header className="topbar">
<div className="project-cluster">
<IconButton label={t("collapseSidebar")} active={compactRail} onClick={() => setCompactRail((v) => !v)}>
<SlidersHorizontal size={19} />
</IconButton>
<div>
<div className="project-title">{t("projectTitle")}</div>
<div className="autosave">
<ShieldCheck size={13} weight="fill" />
{t("autosave")} · {lastSaved}
</div>
</div>
</div>
<div className="topbar-center">
<button className="ghost-action" type="button" onClick={undo}>
<ArrowCounterClockwise size={16} />
{t("undo")}
</button>
<button className="ghost-action" type="button" onClick={redo}>
<ArrowClockwise size={16} />
{t("redo")}
</button>
<span className="divider" />
<div className="menu-anchor">
<button
className="ratio-select"
type="button"
onClick={() => setShowRatioMenu((open) => !open)}
>
{ratio.label} <CaretDown size={14} />
</button>
{showRatioMenu ? (
<Popover onClose={() => setShowRatioMenu(false)}>
<div className="menu-list">
{RATIO_OPTIONS.map((option) => (
<button
type="button"
className={option.id === ratioId ? "is-selected" : ""}
key={option.id}
onClick={() => {
setRatioId(option.id);
setShowRatioMenu(false);
notify(`画布比例已切换为 ${option.label}`);
}}
>
{option.label}
<span>
{option.width} x {option.height}
</span>
</button>
))}
</div>
</Popover>
) : null}
</div>
</div>
<div className="topbar-actions">
<button className="preview-button" type="button" onClick={handlePlayToggle}>
{isPlaying ? <Pause size={16} weight="fill" /> : <Play size={16} weight="fill" />}
{t("preview")}
</button>
<button className="export-button" type="button" disabled={!imageSrc || exporting} onClick={handleExportVideo}>
<FileArrowDown size={17} weight="bold" />
{exporting ? t("exporting") : t("exportMp4")}
</button>
<div className="menu-anchor">
<IconButton label={t("settings")} active={showSettings} onClick={() => setShowSettings((open) => !open)}>
<GearSix size={19} />
</IconButton>
{showSettings ? (
<Popover onClose={() => setShowSettings(false)}>
<div className="settings-panel">
<strong>{t("exportSettings")}</strong>
<label>
<span>{t("language")}</span>
<select
value={activeLanguage}
onChange={(event) => {
const nextLanguage = event.target.value;
saveLanguagePreference(nextLanguage);
setUiLanguage(nextLanguage);
}}
>
{APP_LANGUAGES.map((language) => (
<option value={language.id} key={language.id}>
{language.nativeName}
</option>
))}
</select>
</label>
<label>
<input
type="checkbox"
checked={captionsEnabled}
onChange={(event) => setCaptionsEnabled(event.target.checked)}
/>
{t("exportCaptions")}
</label>
<label>
<input
type="checkbox"
checked={trackVisibility.audio}
onChange={() => toggleTrackVisibility("audio")}
/>
{t("enableAudioTrack")}
</label>
<label>
<input
type="checkbox"
checked={trackVisibility.source}
onChange={() => toggleTrackVisibility("source")}
/>
{t("enableSourceTrack")}
</label>
<label>
<input
type="checkbox"
checked={trackVisibility.music}
onChange={() => toggleTrackVisibility("music")}
/>
{t("enableMusicTrack")}
</label>
<button type="button" onClick={() => notify("模型会由浏览器自动缓存到本地存储")}>
{t("checkModelCache")}
</button>
</div>
</Popover>
) : null}
</div>
</div>
</header>
);
}
+213
View File
@@ -0,0 +1,213 @@
import { HistoryPanel, MyVoicesPanel, VoiceSynthesisPanel } from "./panels.jsx";
export function VoicePanel({
t,
status,
statusText,
voiceTab,
setVoiceTab,
script,
updateScript,
selectedVoiceId,
setSelectedVoiceId,
selectedVoice,
filteredVoices,
voiceFilter,
setVoiceFilter,
showVoiceFilter,
setShowVoiceFilter,
speed,
setSpeed,
volume,
setVolume,
progressPercent,
audioBlob,
generateVoiceover,
downloadBlob,
favoriteVoiceIds,
setFavoriteVoiceIds,
recordedVoices,
recordingState,
recordingElapsed,
startVoiceRecording,
stopVoiceRecording,
useRecordedVoice,
historyItems,
useHistoryItem,
setHistoryItems,
notify,
audioUrl,
audioRef,
setIsPlaying,
sourceAudioRef,
musicRef,
previewVideoRef,
sourceAudioUrl,
trackVisibility,
musicUrl,
setCurrentTime,
}) {
return (
<aside className="voice-panel">
<div className="panel-title-row">
<h1>{t("aiVoice")}</h1>
<span className={`status-pill ${status}`}>
{statusText === "模型待命" ? t("modelReady") : statusText}
</span>
</div>
<div className="tabs compact">
{[
["synthesis", t("voiceSynthesis")],
["mine", t("myVoices")],
["history", t("history")],
].map(([id, label]) => (
<button
className={voiceTab === id ? "is-active" : ""}
type="button"
key={id}
onClick={() => setVoiceTab(id)}
>
{label}
</button>
))}
</div>
<div className="voice-tab-body">
{voiceTab === "synthesis" ? (
<VoiceSynthesisPanel
script={script}
updateScript={updateScript}
selectedVoiceId={selectedVoiceId}
setSelectedVoiceId={setSelectedVoiceId}
selectedVoice={selectedVoice}
filteredVoices={filteredVoices}
voiceFilter={voiceFilter}
setVoiceFilter={setVoiceFilter}
showVoiceFilter={showVoiceFilter}
setShowVoiceFilter={setShowVoiceFilter}
speed={speed}
setSpeed={setSpeed}
volume={volume}
setVolume={setVolume}
status={status}
progressPercent={progressPercent}
audioBlob={audioBlob}
generateVoiceover={generateVoiceover}
downloadBlob={downloadBlob}
favoriteVoiceIds={favoriteVoiceIds}
setFavoriteVoiceIds={setFavoriteVoiceIds}
t={t}
/>
) : null}
{voiceTab === "mine" ? (
<MyVoicesPanel
favoriteVoiceIds={favoriteVoiceIds}
setFavoriteVoiceIds={setFavoriteVoiceIds}
setSelectedVoiceId={setSelectedVoiceId}
selectedVoiceId={selectedVoiceId}
notify={notify}
t={t}
recordedVoices={recordedVoices}
recordingState={recordingState}
recordingElapsed={recordingElapsed}
startVoiceRecording={startVoiceRecording}
stopVoiceRecording={stopVoiceRecording}
useRecordedVoice={useRecordedVoice}
downloadBlob={downloadBlob}
/>
) : null}
{voiceTab === "history" ? (
<HistoryPanel
historyItems={historyItems}
useHistoryItem={useHistoryItem}
setHistoryItems={setHistoryItems}
downloadBlob={downloadBlob}
t={t}
/>
) : null}
</div>
{audioUrl ? (
<audio
ref={audioRef}
src={audioUrl}
onPlay={() => setIsPlaying(true)}
onPause={() => {
setIsPlaying(false);
sourceAudioRef.current?.pause();
musicRef.current?.pause();
previewVideoRef.current?.pause();
}}
onEnded={() => {
setIsPlaying(false);
sourceAudioRef.current?.pause();
musicRef.current?.pause();
previewVideoRef.current?.pause();
}}
onTimeUpdate={(event) => setCurrentTime(event.currentTarget.currentTime)}
/>
) : null}
{sourceAudioUrl ? (
<audio
ref={sourceAudioRef}
src={sourceAudioUrl}
onPlay={() => {
if (!audioUrl || !trackVisibility.audio) {
setIsPlaying(true);
}
}}
onPause={() => {
if (!audioUrl || !trackVisibility.audio) {
setIsPlaying(false);
musicRef.current?.pause();
previewVideoRef.current?.pause();
}
}}
onEnded={() => {
if (!audioUrl || !trackVisibility.audio) {
setIsPlaying(false);
musicRef.current?.pause();
previewVideoRef.current?.pause();
}
}}
onTimeUpdate={(event) => {
if (!audioUrl || !trackVisibility.audio) {
setCurrentTime(event.currentTarget.currentTime);
}
}}
/>
) : null}
{musicUrl ? (
<audio
ref={musicRef}
src={musicUrl}
onPlay={() => {
if ((!audioUrl || !trackVisibility.audio) && (!sourceAudioUrl || !trackVisibility.source)) {
setIsPlaying(true);
}
}}
onPause={() => {
if ((!audioUrl || !trackVisibility.audio) && (!sourceAudioUrl || !trackVisibility.source)) {
setIsPlaying(false);
previewVideoRef.current?.pause();
}
}}
onEnded={() => {
if ((!audioUrl || !trackVisibility.audio) && (!sourceAudioUrl || !trackVisibility.source)) {
setIsPlaying(false);
previewVideoRef.current?.pause();
}
}}
onTimeUpdate={(event) => {
if ((!audioUrl || !trackVisibility.audio) && (!sourceAudioUrl || !trackVisibility.source)) {
setCurrentTime(event.currentTarget.currentTime);
}
}}
/>
) : null}
</aside>
);
}
+829
View File
@@ -0,0 +1,829 @@
import {
CaretDown,
Check,
CloudArrowUp,
DownloadSimple,
MicrophoneStage,
MusicNote,
Pause,
Trash,
Waveform,
} from "@phosphor-icons/react";
import { EFFECT_OPTIONS, FILTER_OPTIONS, SAMPLE_IMAGE, STICKERS, TRANSITIONS, VOICES } from "../config/editor.js";
import { APP_LANGUAGES } from "../i18n.js";
import { formatClock, formatTime, getSegmentStartTime } from "../lib/timeline.js";
import { Popover } from "./ui.jsx";
export function LanguageIntro({ t, closing, onChoose }) {
return (
<div className={`language-intro ${closing ? "is-closing" : ""}`} role="dialog" aria-modal="true">
<div className="language-intro-card">
<div className="language-intro-preview" aria-hidden="true">
<span />
<span />
<span />
</div>
<p>{t("languageKicker")}</p>
<h1>
<span className="language-title-en">Choose interface language</span>
<span className="language-title-local">{t("languageTitle")}</span>
</h1>
<span className="language-intro-copy">
<strong>Pick a language. This choice will be saved for next time.</strong>
<span>{t("languageSubtitle")}</span>
</span>
<div className="language-grid">
{APP_LANGUAGES.map((language) => (
<button type="button" key={language.id} onClick={() => onChoose(language.id)}>
<strong>{language.nativeName}</strong>
<span>{language.hint}</span>
</button>
))}
</div>
<small>{t("languageSaved")}</small>
</div>
</div>
);
}
export function MediaPanel({
t,
mediaTab,
setMediaTab,
isDragging,
setIsDragging,
fileInputRef,
handleFiles,
selectedLibraryAssetId,
builtInAssets,
userAssets,
deleteUserAsset,
draggedAssetId,
handleAssetPointerDown,
handleAssetClick,
}) {
const assets = mediaTab === "library" ? builtInAssets : userAssets;
const renderAssetList = (items, { deletable = false } = {}) => (
<div className={`asset-list ${mediaTab === "upload" ? "upload-assets" : ""}`}>
{items.length ? (
items.map((asset) => (
<div
className={`asset-row-wrap ${draggedAssetId === asset.id ? "is-dragging" : ""}`}
key={asset.id}
>
<button
type="button"
className="asset-row-button"
onPointerDown={(event) => handleAssetPointerDown(event, asset)}
onClick={(event) => handleAssetClick(event, asset)}
>
<AssetRow asset={asset} selected={asset.id === selectedLibraryAssetId} t={t} />
</button>
{deletable ? (
<button
className="asset-delete"
type="button"
aria-label={t("deleteAsset")}
onClick={(event) => {
event.stopPropagation();
deleteUserAsset(asset);
}}
>
<Trash size={15} />
</button>
) : null}
</div>
))
) : (
<div className="empty-state">{t("emptyAssets")}</div>
)}
</div>
);
return (
<>
<div className="tabs">
{[
["upload", t("uploadTab")],
["library", t("libraryTab")],
["mine", t("mineTab")],
].map(([id, label]) => (
<button className={mediaTab === id ? "is-active" : ""} type="button" key={id} onClick={() => setMediaTab(id)}>
{label}
</button>
))}
</div>
{mediaTab === "upload" ? (
<>
<button
className={`drop-zone ${isDragging ? "is-dragging" : ""}`}
type="button"
onClick={() => fileInputRef.current?.click()}
onDragEnter={(event) => {
event.preventDefault();
setIsDragging(true);
}}
onDragOver={(event) => event.preventDefault()}
onDragLeave={() => setIsDragging(false)}
onDrop={(event) => {
event.preventDefault();
setIsDragging(false);
handleFiles(event.dataTransfer.files);
}}
>
<CloudArrowUp size={42} />
<strong>{t("uploadDropTitle")}</strong>
<span>{t("uploadSupport")}</span>
</button>
<input
ref={fileInputRef}
className="sr-only"
type="file"
accept="image/png,image/jpeg,image/webp,video/mp4,video/webm,video/quicktime,audio/mpeg,audio/wav,audio/mp4,audio/aac,audio/ogg"
multiple
onChange={(event) => {
handleFiles(event.target.files);
event.target.value = "";
}}
/>
{renderAssetList(userAssets, { deletable: true })}
</>
) : (
renderAssetList(assets, { deletable: mediaTab === "mine" })
)}
</>
);
}
function AssetRow({ asset, selected, t }) {
return (
<div className={`asset-card ${selected ? "is-selected" : ""}`}>
<div className="asset-thumb">
{asset.type === "video" ? (
<video src={asset.src} muted playsInline preload="metadata" draggable={false} />
) : asset.type === "audio" ? (
<div className="asset-audio-thumb">
<MusicNote size={28} weight="duotone" />
</div>
) : (
<img src={asset.src} alt="" draggable={false} />
)}
<span>
{asset.type === "audio"
? t("assetAudio")
: asset.type === "video"
? t("assetVideo")
: t("assetImage")}
</span>
</div>
<div>
<strong>{asset.name}</strong>
<span>{asset.meta}</span>
</div>
</div>
);
}
export function ToolPanel(props) {
const {
activeTool,
script,
updateScript,
segments,
currentSegmentIndex,
captionSegments,
captionTargetDuration,
selectedCaptionSegment,
selectedSegmentId,
setSelectedSegmentId,
updateCaptionSegmentText,
toggleCaptionSegmentHidden,
deleteCaptionSegment,
seekTo,
estimatedDuration,
captionPosition,
setCaptionPosition,
captionSize,
setCaptionSize,
captionsEnabled,
setCaptionsEnabled,
selectedFilterId,
setSelectedFilterId,
selectedTransitionId,
setSelectedTransitionId,
selectedStickerId,
setSelectedStickerId,
audioBlob,
audioDuration,
sourceAudioBlob,
sourceAudioName,
sourceAudioDuration,
sourceAudioVolume,
setSourceAudioVolume,
clearSourceAudioTrack,
musicBlob,
musicName,
musicDuration,
musicVolume,
setMusicVolume,
clearMusicTrack,
selectedVoice,
setVoiceTab,
downloadBlob,
notify,
t,
trOption,
} = props;
if (activeTool === "text") {
return (
<div className="tool-panel">
<h2>{t("text")}</h2>
<textarea className="side-textarea" value={script} onChange={(event) => updateScript(event.target.value)} />
<div className="quick-grid">
{[
["openingHook", t("openingHook")],
["productPoint", t("productPoint")],
["actionGuide", t("actionGuide")],
].map(([id, item]) => (
<button
type="button"
key={id}
onClick={() => updateScript(`${script.trim()}\n${item}: ${t("templateSuffix")}`.trim())}
>
{item}
</button>
))}
</div>
</div>
);
}
if (activeTool === "caption") {
return (
<div className="tool-panel">
<h2>{t("caption")}</h2>
<label className="switch-row">
<input type="checkbox" checked={captionsEnabled} onChange={(event) => setCaptionsEnabled(event.target.checked)} />
{t("showCaptions")}
</label>
<div className="segmented">
{["top", "middle", "bottom"].map((position) => (
<button
className={captionPosition === position ? "is-active" : ""}
type="button"
key={position}
onClick={() => setCaptionPosition(position)}
>
{position === "top" ? t("top") : position === "middle" ? t("middle") : t("bottom")}
</button>
))}
</div>
<div className="slider-field compact-slider">
<div>
<label htmlFor="caption-size">{t("fontSize")}</label>
<span>{captionSize}px</span>
</div>
<input
id="caption-size"
type="range"
min="20"
max="42"
step="1"
value={captionSize}
onChange={(event) => setCaptionSize(Number(event.target.value))}
/>
</div>
{selectedCaptionSegment ? (
<div className="caption-editor">
<label htmlFor="caption-editor">{t("currentCaption")}</label>
<textarea
id="caption-editor"
value={selectedCaptionSegment.text}
onChange={(event) => updateCaptionSegmentText(selectedCaptionSegment.id, event.target.value)}
/>
<label className="switch-row">
<input
type="checkbox"
checked={!selectedCaptionSegment.hidden}
onChange={() => toggleCaptionSegmentHidden(selectedCaptionSegment.id)}
/>
{t("showCurrentCaption")}
</label>
<button
className="panel-danger"
type="button"
onClick={() => deleteCaptionSegment(selectedCaptionSegment.id)}
>
<Trash size={15} />
{t("deleteCurrentCaption")}
</button>
</div>
) : null}
<div className="segment-list">
{captionSegments.length ? (
captionSegments.map((segment, index) => (
<button
type="button"
className={`${index === currentSegmentIndex ? "is-current" : ""} ${
segment.id === selectedSegmentId ? "is-selected" : ""
} ${segment.hidden ? "is-hidden" : ""}`}
key={segment.id}
onClick={() => {
setSelectedSegmentId(segment.id);
seekTo(getSegmentStartTime(captionSegments, index, captionTargetDuration));
}}
>
{segment.text}
</button>
))
) : (
<div className="empty-state">{t("noCaptionSegments")}</div>
)}
</div>
</div>
);
}
if (activeTool === "audio") {
return (
<div className="tool-panel">
<h2>{t("audioPanel")}</h2>
<button
className="audio-entry-card"
type="button"
onClick={() => {
setVoiceTab("synthesis");
notify("已打开 AI 配音");
}}
>
<MicrophoneStage size={24} weight="duotone" />
<span>
<strong>{t("aiVoiceEntryTitle")}</strong>
<em>{t("aiVoiceEntryDesc")}</em>
</span>
</button>
<div className="metric-list">
<div>
<span>{t("currentVoice")}</span>
<strong>{selectedVoice.name}</strong>
</div>
<div>
<span>{t("voiceDuration")}</span>
<strong>{formatTime(audioBlob ? audioDuration : 0)}</strong>
</div>
<div>
<span>{t("sourceAudio")}</span>
<strong>{sourceAudioBlob ? sourceAudioName : t("notSeparated")}</strong>
</div>
<div>
<span>{t("sourceDuration")}</span>
<strong>{formatTime(sourceAudioBlob ? sourceAudioDuration : 0)}</strong>
</div>
<div>
<span>{t("bgm")}</span>
<strong>{musicBlob ? musicName : t("notAdded")}</strong>
</div>
<div>
<span>{t("musicDuration")}</span>
<strong>{formatTime(musicBlob ? musicDuration : 0)}</strong>
</div>
</div>
<div className="slider-field compact-slider">
<div>
<label htmlFor="source-audio-volume">{t("sourceAudio")} {t("volume")}</label>
<span>{Math.round(sourceAudioVolume * 100)}%</span>
</div>
<input
id="source-audio-volume"
type="range"
min="0"
max="1"
step="0.01"
value={sourceAudioVolume}
disabled={!sourceAudioBlob}
onInput={(event) => setSourceAudioVolume(Number(event.currentTarget.value))}
onChange={(event) => setSourceAudioVolume(Number(event.target.value))}
/>
</div>
<div className="slider-field compact-slider">
<div>
<label htmlFor="music-volume">{t("bgm")} {t("volume")}</label>
<span>{Math.round(musicVolume * 100)}%</span>
</div>
<input
id="music-volume"
type="range"
min="0"
max="1"
step="0.01"
value={musicVolume}
onInput={(event) => setMusicVolume(Number(event.currentTarget.value))}
onChange={(event) => setMusicVolume(Number(event.target.value))}
/>
</div>
<button
className="panel-primary"
type="button"
disabled={!audioBlob}
onClick={() => audioBlob && downloadBlob(audioBlob, "ai-voiceover.wav")}
>
{t("downloadCurrentWav")}
</button>
<button
className="panel-secondary"
type="button"
disabled={!musicBlob}
onClick={() => musicBlob && downloadBlob(musicBlob, musicName || "background-music.wav")}
>
{t("downloadBgm")}
</button>
<button
className="panel-secondary"
type="button"
disabled={!sourceAudioBlob}
onClick={() => sourceAudioBlob && downloadBlob(sourceAudioBlob, sourceAudioName || "source-audio.wav")}
>
{t("downloadSource")}
</button>
<button className="panel-secondary" type="button" disabled={!sourceAudioBlob} onClick={() => clearSourceAudioTrack()}>
{t("deleteSource")}
</button>
<button className="panel-secondary" type="button" disabled={!musicBlob} onClick={() => clearMusicTrack()}>
{t("deleteBgm")}
</button>
</div>
);
}
if (activeTool === "transition") {
return (
<VisualChoicePanel
title={t("transition")}
kind="transition"
options={TRANSITIONS}
selectedId={selectedTransitionId}
trOption={trOption}
onSelect={(id) => {
setSelectedTransitionId(id);
notify(t("transitionApplied"));
}}
/>
);
}
if (activeTool === "effects") {
return (
<VisualChoicePanel
title={t("effects")}
kind="effect"
options={EFFECT_OPTIONS}
selectedId={selectedFilterId}
trOption={trOption}
onSelect={(id) => {
setSelectedFilterId(id);
notify(t("effectApplied"));
}}
/>
);
}
if (activeTool === "stickers") {
return (
<ChoicePanel
title={t("stickers")}
options={STICKERS}
selectedId={selectedStickerId}
trOption={trOption}
onSelect={(id) => {
setSelectedStickerId(id);
notify(t("stickerApplied"));
}}
/>
);
}
return (
<VisualChoicePanel
title={t("filters")}
kind="effect"
options={FILTER_OPTIONS}
selectedId={selectedFilterId}
trOption={trOption}
onSelect={(id) => {
setSelectedFilterId(id);
notify(t("filterApplied"));
}}
/>
);
}
function VisualChoicePanel({ title, kind, options, selectedId, trOption = (name) => name, onSelect }) {
return (
<div className="tool-panel">
<h2>{title}</h2>
<div className="visual-choice-grid">
{options.map((option) => (
<button
className={`visual-choice-card is-${kind} preview-${option.id} ${
selectedId === option.id ? "is-selected" : ""
}`}
type="button"
key={option.id}
style={{
"--choice-image": `url(${SAMPLE_IMAGE})`,
"--choice-filter": option.css ?? "none",
}}
onClick={() => onSelect(option.id)}
>
<span className="visual-choice-thumb" aria-hidden="true" />
<span className="visual-choice-label">
<span>{trOption(option.name)}</span>
{selectedId === option.id ? <Check size={14} weight="bold" /> : null}
</span>
</button>
))}
</div>
</div>
);
}
function ChoicePanel({ title, options, selectedId, trOption = (name) => name, onSelect }) {
return (
<div className="tool-panel">
<h2>{title}</h2>
<div className="choice-list">
{options.map((option) => (
<button className={selectedId === option.id ? "is-selected" : ""} type="button" key={option.id} onClick={() => onSelect(option.id)}>
<span>{trOption(option.name)}</span>
{selectedId === option.id ? <Check size={16} /> : null}
</button>
))}
</div>
</div>
);
}
export function VoiceSynthesisPanel({
script,
updateScript,
selectedVoiceId,
setSelectedVoiceId,
selectedVoice,
filteredVoices,
voiceFilter,
setVoiceFilter,
showVoiceFilter,
setShowVoiceFilter,
speed,
setSpeed,
volume,
setVolume,
status,
progressPercent,
audioBlob,
generateVoiceover,
downloadBlob,
favoriteVoiceIds,
setFavoriteVoiceIds,
t,
}) {
return (
<>
<label className="field-label" htmlFor="script-input">
{t("inputScript")}
</label>
<div className="script-box">
<textarea id="script-input" value={script} maxLength={5000} onChange={(event) => updateScript(event.target.value)} />
<div className="script-meta">
<button type="button" onClick={() => updateScript("")}>
<Trash size={14} />
{t("clear")}
</button>
<span>{script.length} / 5000</span>
</div>
</div>
<div className="voice-header">
<label className="field-label">{t("chooseVoice")}</label>
<div className="menu-anchor">
<button className="voice-filter" type="button" onClick={() => setShowVoiceFilter((open) => !open)}>
{voiceFilter === "all" ? t("allVoices") : voiceFilter} <CaretDown size={14} />
</button>
{showVoiceFilter ? (
<Popover onClose={() => setShowVoiceFilter(false)}>
<div className="menu-list">
{["all", "中文", "English", "piper", "kokoro"].map((filter) => (
<button
type="button"
className={voiceFilter === filter ? "is-selected" : ""}
key={filter}
onClick={() => {
setVoiceFilter(filter);
setShowVoiceFilter(false);
}}
>
{filter === "all" ? t("allVoices") : filter}
</button>
))}
</div>
</Popover>
) : null}
</div>
</div>
<div className="voice-list">
{filteredVoices.map((voice) => (
<button
className={`voice-card ${voice.id === selectedVoiceId ? "is-selected" : ""}`}
type="button"
key={voice.id}
onClick={() => setSelectedVoiceId(voice.id)}
>
<span className="avatar">
<MicrophoneStage size={17} weight="fill" />
</span>
<span>
<strong>{voice.name}</strong>
<em>
{voice.language} · {voice.gender}
</em>
</span>
<small>{voice.badge}</small>
</button>
))}
</div>
<div className="model-row">
<span>{selectedVoice.detail}</span>
<button
type="button"
onClick={() =>
setFavoriteVoiceIds((ids) =>
ids.includes(selectedVoiceId) ? ids.filter((id) => id !== selectedVoiceId) : [...ids, selectedVoiceId],
)
}
>
{favoriteVoiceIds.includes(selectedVoiceId) ? t("saved") : t("favoriteVoice")}
</button>
</div>
<div className="slider-field">
<div>
<label htmlFor="speed">{t("speed")}</label>
<span>{speed.toFixed(2)} x</span>
</div>
<input id="speed" type="range" min="0.7" max="1.3" step="0.05" value={speed} onChange={(event) => setSpeed(Number(event.target.value))} />
</div>
<div className="slider-field">
<div>
<label htmlFor="volume">{t("volume")}</label>
<span>{Math.round(volume * 100)}%</span>
</div>
<input id="volume" type="range" min="0" max="1" step="0.01" value={volume} onChange={(event) => setVolume(Number(event.target.value))} />
</div>
{status === "generating" ? (
<div className="progress-track" aria-label={t("generationProgress")}>
<span style={{ width: `${progressPercent}%` }} />
</div>
) : null}
<div className="voice-actions">
<button className="generate-button" type="button" disabled={status === "generating" || !script.trim()} onClick={generateVoiceover}>
<Waveform size={18} weight="bold" />
{status === "generating" ? t("generating") : audioBlob ? t("regenerateVoice") : t("generateVoice")}
</button>
<button className="secondary-download" type="button" disabled={!audioBlob} onClick={() => audioBlob && downloadBlob(audioBlob, "ai-voiceover.wav")}>
<DownloadSimple size={17} />
</button>
</div>
</>
);
}
export function MyVoicesPanel({
favoriteVoiceIds,
setFavoriteVoiceIds,
setSelectedVoiceId,
selectedVoiceId,
notify,
t,
recordedVoices,
recordingState,
recordingElapsed,
startVoiceRecording,
stopVoiceRecording,
useRecordedVoice,
downloadBlob,
}) {
const favorites = VOICES.filter((voice) => favoriteVoiceIds.includes(voice.id));
const isRecording = recordingState === "recording";
const isProcessingRecording = recordingState === "processing";
return (
<div className="history-panel">
<div className={`record-card ${isRecording ? "is-recording" : ""}`}>
<div>
<strong>{t("recordVoice")}</strong>
<span>{isRecording ? `${t("recording")} · ${formatClock(recordingElapsed)}` : t("noRecordings")}</span>
</div>
<button
type="button"
disabled={isProcessingRecording}
onClick={isRecording ? stopVoiceRecording : startVoiceRecording}
>
{isRecording ? <Pause size={15} weight="fill" /> : <MicrophoneStage size={15} weight="fill" />}
{isRecording ? t("stopRecording") : isProcessingRecording ? t("generating") : t("startRecording")}
</button>
</div>
{recordedVoices.length ? (
<>
<div className="panel-subtitle">{t("recordedVoices")}</div>
{recordedVoices.map((recording) => (
<div className="history-item is-recording-item" key={recording.id}>
<div>
<strong>{recording.name}</strong>
<span>
{recording.createdAt} · {formatTime(recording.duration)}
</span>
</div>
<button type="button" onClick={() => useRecordedVoice(recording)}>
{t("use")}
</button>
<button
type="button"
onClick={() => downloadBlob(recording.blob, `${recording.name}.${recording.extension}`)}
>
{t("download")}
</button>
</div>
))}
</>
) : null}
<div className="panel-subtitle">{t("favoriteVoice")}</div>
{favorites.length ? (
favorites.map((voice) => (
<div className={`history-item ${selectedVoiceId === voice.id ? "is-selected" : ""}`} key={voice.id}>
<div>
<strong>{voice.name}</strong>
<span>
{voice.language} · {voice.detail}
</span>
</div>
<button
type="button"
onClick={() => {
setSelectedVoiceId(voice.id);
notify("已切换到收藏声音");
}}
>
{t("use")}
</button>
<button type="button" onClick={() => setFavoriteVoiceIds((ids) => ids.filter((id) => id !== voice.id))}>
{t("remove")}
</button>
</div>
))
) : (
<div className="empty-state">{t("noFavoriteVoices")}</div>
)}
</div>
);
}
export function HistoryPanel({ historyItems, useHistoryItem, setHistoryItems, downloadBlob, t }) {
return (
<div className="history-panel">
{historyItems.length ? (
historyItems.map((item) => (
<div className="history-item" key={item.id}>
<div>
<strong>{item.voiceName}</strong>
<span>
{item.createdAt} · {formatTime(item.duration)} · {item.script.slice(0, 18)}
</span>
</div>
<button type="button" onClick={() => useHistoryItem(item)}>
{t("use")}
</button>
<button type="button" onClick={() => downloadBlob(item.blob, `history-${item.voiceName}.wav`)}>
{t("download")}
</button>
<button type="button" onClick={() => setHistoryItems((items) => items.filter((entry) => entry.id !== item.id))}>
{t("delete")}
</button>
</div>
))
) : (
<div className="empty-state">{t("noMediaHistory")}</div>
)}
</div>
);
}
+40
View File
@@ -0,0 +1,40 @@
import { X } from "@phosphor-icons/react";
export function IconButton({ label, children, active = false, disabled = false, onClick }) {
return (
<button
className={`icon-button ${active ? "is-active" : ""}`}
type="button"
aria-label={label}
title={label}
disabled={disabled}
onClick={onClick}
>
{children}
</button>
);
}
export function Popover({ children, onClose }) {
return (
<div className="popover" role="dialog">
<button className="popover-close" type="button" aria-label="关闭" onClick={onClose}>
<X size={14} />
</button>
{children}
</div>
);
}
export function WaveformStrip({ peaks, active = false, hidden = false }) {
return (
<div
className={`waveform-strip ${active ? "is-active" : ""} ${hidden ? "is-muted" : ""}`}
aria-hidden="true"
>
{peaks.map((peak, index) => (
<span key={`${index}-${peak}`} style={{ "--bar": peak }} />
))}
</div>
);
}
+164
View File
@@ -0,0 +1,164 @@
import {
CirclesThree,
ClosedCaptioning,
ImageSquare,
MagicWand,
MusicNote,
Sparkle,
Sticker,
TextT,
} from "@phosphor-icons/react";
export const SAMPLE_IMAGE = "/assets/sample-portrait.png";
export const MODEL_ID = "onnx-community/Kokoro-82M-v1.0-ONNX";
export const FFMPEG_CLASS_WORKER_URL = "https://cdn.jsdelivr.net/npm/@ffmpeg/ffmpeg@0.12.15/dist/esm/worker.js";
export const FFMPEG_CORE_BASE_URL = "https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.10/dist/esm";
export const MAX_TIMELINE_DURATION_SECONDS = 30 * 60;
export const IMAGE_SEGMENT_SECONDS = 2;
export const MIN_VISUAL_SEGMENT_SECONDS = 0.5;
export const MAX_IMAGE_THUMBNAILS = 80;
export const IMAGE_RESIZE_OVERFLOW_SECONDS_PER_PIXEL = 0.05;
export const IMAGE_SNAP_THRESHOLD_PIXELS = 16;
export const MIN_CAPTION_SEGMENT_SECONDS = 1.2;
export const MAX_CAPTION_SEGMENT_SECONDS = 12;
export const SUPPORTED_MEDIA_TYPES = ["image/", "video/", "audio/"];
export const ASSET_DRAG_MIME = "application/x-ai-voiceover-asset";
export const DEFAULT_SCRIPT = "";
export const EXPORT_RECORDING_FORMATS = [
{
mimeType: "video/mp4;codecs=avc1.42E01E,mp4a.40.2",
extension: "mp4",
label: "MP4",
},
{
mimeType: "video/mp4;codecs=h264,aac",
extension: "mp4",
label: "MP4",
},
{
mimeType: "video/mp4",
extension: "mp4",
label: "MP4",
},
{
mimeType: "video/webm;codecs=vp9,opus",
extension: "webm",
label: "WebM",
},
{
mimeType: "video/webm;codecs=vp8,opus",
extension: "webm",
label: "WebM",
},
{
mimeType: "video/webm",
extension: "webm",
label: "WebM",
},
];
export const AUDIO_RECORDING_FORMATS = [
{ mimeType: "audio/webm;codecs=opus", extension: "webm" },
{ mimeType: "audio/webm", extension: "webm" },
{ mimeType: "audio/ogg;codecs=opus", extension: "ogg" },
{ mimeType: "audio/mp4", extension: "m4a" },
];
export const VOICES = [
{
id: "zh_CN-huayan-medium",
name: "华言",
language: "中文",
detail: "Piper ONNX · 普通话",
gender: "温柔女声",
engine: "piper",
badge: "推荐",
},
{
id: "zh_CN-huayan-x_low",
name: "轻量华言",
language: "中文",
detail: "Piper ONNX · 小模型",
gender: "快速预览",
engine: "piper",
badge: "轻量",
},
{
id: "af_heart",
name: "Heart",
language: "English",
detail: "Kokoro 82M · q8",
gender: "Warm female",
engine: "kokoro",
badge: "ONNX",
},
{
id: "am_fenrir",
name: "Fenrir",
language: "English",
detail: "Kokoro 82M · q8",
gender: "Steady male",
engine: "kokoro",
badge: "ONNX",
},
];
export const TOOL_RAIL = [
{ id: "media", label: "媒体", icon: ImageSquare },
{ id: "text", label: "文本", icon: TextT },
{ id: "caption", label: "字幕", icon: ClosedCaptioning },
{ id: "audio", label: "音频", icon: MusicNote },
{ id: "transition", label: "转场", icon: CirclesThree },
{ id: "effects", label: "效果", icon: Sparkle },
{ id: "stickers", label: "贴纸", icon: Sticker },
{ id: "filters", label: "滤镜", icon: MagicWand },
];
export const RATIO_OPTIONS = [
{ id: "16:9", label: "16:9", width: 1280, height: 720 },
{ id: "9:16", label: "9:16", width: 720, height: 1280 },
{ id: "1:1", label: "1:1", width: 1080, height: 1080 },
{ id: "4:5", label: "4:5", width: 1080, height: 1350 },
];
export const FILTER_OPTIONS = [
{ id: "none", name: "原片", css: "none" },
{ id: "cool", name: "冷调清透", css: "contrast(1.04) saturate(0.96) hue-rotate(8deg)" },
{ id: "film", name: "胶片暗角", css: "contrast(1.12) saturate(0.82) brightness(0.92)" },
{ id: "bright", name: "轻亮人像", css: "brightness(1.08) contrast(0.98) saturate(1.05)" },
];
export const EFFECT_OPTIONS = [
{ id: "effect-clean", name: "清晰增强", css: "contrast(1.08) saturate(1.08) brightness(1.03)" },
{ id: "effect-soft", name: "柔光", css: "brightness(1.08) contrast(0.94) saturate(1.06)" },
{ id: "effect-cinematic", name: "电影感", css: "contrast(1.18) saturate(0.86) brightness(0.92)" },
{ id: "effect-vivid", name: "高饱和", css: "contrast(1.08) saturate(1.28)" },
{ id: "effect-night", name: "夜景", css: "brightness(0.82) contrast(1.2) saturate(1.08)" },
{ id: "effect-warm", name: "暖调", css: "sepia(0.16) saturate(1.12) brightness(1.04)" },
{ id: "effect-cold", name: "冷蓝", css: "hue-rotate(12deg) saturate(0.98) contrast(1.06)" },
{ id: "effect-noir", name: "黑白", css: "grayscale(1) contrast(1.18)" },
{ id: "effect-dream", name: "梦幻", css: "brightness(1.1) saturate(1.18) blur(0.2px)" },
];
export const VISUAL_STYLE_OPTIONS = [...FILTER_OPTIONS, ...EFFECT_OPTIONS];
export const TRANSITIONS = [
{ id: "none", name: "无转场" },
{ id: "fade", name: "淡入淡出" },
{ id: "zoom", name: "轻推拉" },
{ id: "flash", name: "闪白切换" },
{ id: "wipe-left", name: "左推入" },
{ id: "wipe-up", name: "上推入" },
{ id: "blur", name: "模糊切" },
{ id: "split", name: "双开门" },
{ id: "glitch", name: "故障闪" },
];
export const STICKERS = [
{ id: "none", name: "无贴纸", text: "" },
{ id: "new", name: "新品感", text: "NEW" },
{ id: "hot", name: "热点", text: "HOT" },
{ id: "note", name: "旁白", text: "AI VOICE" },
];
+760
View File
@@ -0,0 +1,760 @@
export const LANGUAGE_STORAGE_KEY = "ai-voiceover-ui-language";
export const APP_LANGUAGES = [
{ id: "zh", name: "中文", nativeName: "中文", hint: "简体中文" },
{ id: "en", name: "English", nativeName: "English", hint: "English" },
{ id: "ja", name: "Japanese", nativeName: "日本語", hint: "Japanese" },
{ id: "ko", name: "Korean", nativeName: "한국어", hint: "Korean" },
{ id: "es", name: "Spanish", nativeName: "Español", hint: "Spanish" },
{ id: "fr", name: "French", nativeName: "Français", hint: "French" },
{ id: "de", name: "German", nativeName: "Deutsch", hint: "German" },
{ id: "pt", name: "Portuguese", nativeName: "Português", hint: "Portuguese" },
{ id: "th", name: "Thai", nativeName: "ไทย", hint: "Thai" },
{ id: "vi", name: "Vietnamese", nativeName: "Tiếng Việt", hint: "Vietnamese" },
];
export const UI_COPY = {
zh: {
languageKicker: "AI Voice Studio",
languageTitle: "选择界面语言",
languageSubtitle: "设置一次后会自动保存,下次进入直接使用该语言。",
languageSaved: "之后可在设置里修改",
projectTitle: "AI 配音项目",
autosave: "已自动保存",
collapseSidebar: "折叠侧栏",
undo: "撤销",
redo: "重做",
preview: "预览",
pause: "暂停",
play: "播放",
exporting: "导出中",
exportMp4: "导出 MP4",
settings: "设置",
exportSettings: "导出设置",
exportCaptions: "导出字幕",
enableAudioTrack: "启用音频轨",
enableSourceTrack: "启用视频原声轨",
enableMusicTrack: "启用背景音乐轨",
checkModelCache: "检查模型缓存",
language: "语言",
toolbar: "工具栏",
media: "媒体",
text: "文本",
caption: "字幕",
audio: "音频",
transition: "转场",
effects: "效果",
stickers: "贴纸",
filters: "滤镜",
uploadTab: "本地上传",
libraryTab: "素材库",
mineTab: "我的素材",
uploadDropTitle: "点击上传或拖拽图片/视频/音频到此处",
uploadSupport: "支持 JPG、PNG、WebP、MP4、WebM、MOV、MP3、WAV、M4A",
emptyAssets: "上传图片或视频后,这里会显示你的本地素材。",
previewEmptyTitle: "上传图片或视频开始剪辑",
previewEmptySubtitle: "时间线默认保持为空",
currentMediaAlt: "当前上传素材预览",
fit: "适合",
cover: "填充",
fullscreenPreview: "全屏预览",
backTwoSeconds: "后退 2 秒",
forwardTwoSeconds: "前进 2 秒",
deleteTrack: "删除选中轨道",
duplicateTrack: "复制选中轨道",
cutSegment: "剪切当前片段",
cropCanvas: "裁剪画面",
addSegment: "片段",
removeSegment: "片段",
shortenSegment: "缩短当前片段",
lengthenSegment: "加长当前片段",
zoomOut: "缩小时间线",
fitTimeline: "缩放适配",
zoomIn: "放大时间线",
imageTrack: "图片",
sourceTrack: "视频原声",
voiceTrack: "配音音频",
musicTrack: "背景音乐",
visible: "可见性",
lock: "锁定",
dragPlayhead: "拖拽播放头",
dragImageDuration: "拖拽调整图片时长",
exportInProgress: "导出中",
exportProgress: "导出进度",
preparingExport: "准备导出",
aiVoice: "AI 语音",
voiceSynthesis: "语音合成",
myVoices: "我的声音",
history: "历史记录",
modelReady: "模型待命",
inputScript: "输入文案",
clear: "清空",
chooseVoice: "选择声音",
allVoices: "全部语音",
speed: "语速",
volume: "音量",
generateVoice: "生成语音",
regenerateVoice: "重新生成语音",
download: "下载",
use: "使用",
remove: "移除",
delete: "删除",
generating: "生成中",
generationProgress: "生成进度",
favoriteVoice: "收藏声音",
favorite: "收藏",
saved: "已收藏",
showCaptions: "显示字幕",
top: "顶部",
middle: "居中",
bottom: "底部",
fontSize: "字号",
currentCaption: "当前字幕",
showCurrentCaption: "显示当前字幕",
deleteCurrentCaption: "删除当前字幕",
noCaptionSegments: "当前没有字幕片段。",
openingHook: "开场强调",
productPoint: "产品卖点",
actionGuide: "行动引导",
templateSuffix: "请替换为你的文案。",
audioPanel: "音频",
aiVoiceEntryTitle: "AI 配音",
aiVoiceEntryDesc: "输入文案、选择声音并生成语音",
currentVoice: "当前声音",
voiceDuration: "配音时长",
sourceAudio: "视频原声",
sourceDuration: "原声时长",
bgm: "背景音乐",
musicDuration: "音乐时长",
notSeparated: "未分离",
notAdded: "未添加",
downloadCurrentWav: "下载当前 WAV",
downloadBgm: "下载背景音乐",
downloadSource: "下载视频原声",
deleteSource: "删除视频原声",
deleteBgm: "删除背景音乐",
transitionApplied: "转场已应用到导出预览状态",
effectApplied: "效果已应用到预览和导出",
stickerApplied: "贴纸已应用到预览和导出",
filterApplied: "画面风格已更新",
noMediaHistory: "生成配音后,历史记录会保存在当前浏览器会话里。",
noFavoriteVoices: "在语音合成里收藏声音后,会显示在这里。",
recordVoice: "录制声音",
startRecording: "开始录音",
stopRecording: "停止录音",
recording: "录音中",
recordedVoices: "我的录音",
noRecordings: "还没有录音。点击开始录音后,会自动写入配音音频轨。",
recordingReady: "录音已写入配音音频轨",
recordingUnsupported: "当前浏览器不支持麦克风录音",
recordingPermissionDenied: "无法访问麦克风,请检查浏览器权限",
assetAudio: "音频",
assetVideo: "视频",
assetImage: "图片",
deleteAsset: "删除素材",
imageHidden: "图片轨已隐藏",
dropVisualHere: "释放到图片轨",
dropVoiceHere: "释放到配音音频轨",
dropSourceHere: "释放后分离视频原声",
dropMusicHere: "释放到背景音乐轨",
},
en: {
languageKicker: "AI Voice Studio",
languageTitle: "Choose Interface Language",
languageSubtitle: "Saved once, then this editor opens in your language next time.",
languageSaved: "You can change it later in Settings",
projectTitle: "AI Voiceover Project",
autosave: "Autosaved",
collapseSidebar: "Collapse sidebar",
undo: "Undo",
redo: "Redo",
preview: "Preview",
pause: "Pause",
play: "Play",
exporting: "Exporting",
exportMp4: "Export MP4",
settings: "Settings",
exportSettings: "Export Settings",
exportCaptions: "Export captions",
enableAudioTrack: "Enable voice track",
enableSourceTrack: "Enable source audio",
enableMusicTrack: "Enable background music",
checkModelCache: "Check model cache",
language: "Language",
toolbar: "Toolbar",
media: "Media",
text: "Text",
caption: "Captions",
audio: "Audio",
transition: "Transitions",
effects: "Effects",
stickers: "Stickers",
filters: "Filters",
uploadTab: "Upload",
libraryTab: "Library",
mineTab: "My assets",
uploadDropTitle: "Click or drop image, video, or audio here",
uploadSupport: "Supports JPG, PNG, WebP, MP4, WebM, MOV, MP3, WAV, M4A",
emptyAssets: "Your local assets will appear here after upload.",
previewEmptyTitle: "Upload image or video to start editing",
previewEmptySubtitle: "Timeline starts empty by default",
currentMediaAlt: "Current uploaded media preview",
fit: "Fit",
cover: "Fill",
fullscreenPreview: "Fullscreen preview",
backTwoSeconds: "Back 2 seconds",
forwardTwoSeconds: "Forward 2 seconds",
deleteTrack: "Delete selected track",
duplicateTrack: "Duplicate selected track",
cutSegment: "Cut current segment",
cropCanvas: "Crop canvas",
addSegment: "Segment",
removeSegment: "Segment",
shortenSegment: "Shorten segment",
lengthenSegment: "Lengthen segment",
zoomOut: "Zoom out",
fitTimeline: "Fit timeline",
zoomIn: "Zoom in",
imageTrack: "Image",
sourceTrack: "Source audio",
voiceTrack: "Voiceover",
musicTrack: "Music",
visible: "visibility",
lock: "lock",
dragPlayhead: "Drag playhead",
dragImageDuration: "Drag to adjust visual duration",
exportInProgress: "Exporting",
exportProgress: "Export progress",
preparingExport: "Preparing export",
aiVoice: "AI Voice",
voiceSynthesis: "Voice synthesis",
myVoices: "My voices",
history: "History",
modelReady: "Model ready",
inputScript: "Script",
clear: "Clear",
chooseVoice: "Choose voice",
allVoices: "All voices",
speed: "Speed",
volume: "Volume",
generateVoice: "Generate voice",
regenerateVoice: "Regenerate voice",
download: "Download",
use: "Use",
remove: "Remove",
delete: "Delete",
generating: "Generating",
generationProgress: "Generation progress",
favoriteVoice: "Favorite voice",
favorite: "Favorite",
saved: "Saved",
showCaptions: "Show captions",
top: "Top",
middle: "Middle",
bottom: "Bottom",
fontSize: "Font size",
currentCaption: "Current caption",
showCurrentCaption: "Show current caption",
deleteCurrentCaption: "Delete current caption",
noCaptionSegments: "No caption segments.",
openingHook: "Opening hook",
productPoint: "Product point",
actionGuide: "Call to action",
templateSuffix: "Replace with your copy.",
audioPanel: "Audio",
aiVoiceEntryTitle: "AI Voiceover",
aiVoiceEntryDesc: "Write script, choose a voice, generate audio",
currentVoice: "Current voice",
voiceDuration: "Voice duration",
sourceAudio: "Source audio",
sourceDuration: "Source duration",
bgm: "Background music",
musicDuration: "Music duration",
notSeparated: "Not separated",
notAdded: "Not added",
downloadCurrentWav: "Download WAV",
downloadBgm: "Download music",
downloadSource: "Download source audio",
deleteSource: "Delete source audio",
deleteBgm: "Delete music",
transitionApplied: "Transition applied to export preview",
effectApplied: "Effect applied to preview and export",
stickerApplied: "Sticker applied to preview and export",
filterApplied: "Visual style updated",
noMediaHistory: "Generated voiceovers will be saved in this browser session.",
noFavoriteVoices: "Favorite voices in synthesis and they will appear here.",
recordVoice: "Record voice",
startRecording: "Start recording",
stopRecording: "Stop recording",
recording: "Recording",
recordedVoices: "My recordings",
noRecordings: "No recordings yet. Start recording and it will be added to the voiceover track.",
recordingReady: "Recording added to the voiceover track",
recordingUnsupported: "This browser does not support microphone recording",
recordingPermissionDenied: "Microphone access failed. Check browser permissions.",
assetAudio: "Audio",
assetVideo: "Video",
assetImage: "Image",
deleteAsset: "Delete asset",
imageHidden: "Image track hidden",
dropVisualHere: "Drop on visual track",
dropVoiceHere: "Drop on voiceover track",
dropSourceHere: "Drop to extract source audio",
dropMusicHere: "Drop on music track",
},
ja: {
languageTitle: "表示言語を選択",
languageSubtitle: "一度保存すると、次回からこの言語で開きます。",
languageSaved: "あとで設定から変更できます",
projectTitle: "AI ナレーションプロジェクト",
autosave: "自動保存済み",
undo: "元に戻す",
redo: "やり直し",
preview: "プレビュー",
pause: "一時停止",
play: "再生",
exporting: "書き出し中",
exportMp4: "MP4 書き出し",
settings: "設定",
media: "メディア",
text: "テキスト",
caption: "字幕",
audio: "音声",
transition: "トランジション",
effects: "エフェクト",
stickers: "ステッカー",
filters: "フィルター",
uploadTab: "アップロード",
libraryTab: "素材",
mineTab: "マイ素材",
uploadDropTitle: "画像・動画・音声をクリックまたはドラッグ",
previewEmptyTitle: "画像または動画をアップロードして開始",
aiVoice: "AI 音声",
voiceSynthesis: "音声合成",
myVoices: "マイ音声",
history: "履歴",
inputScript: "原稿入力",
chooseVoice: "声を選択",
generateVoice: "音声生成",
use: "使用",
remove: "削除",
delete: "削除",
generating: "生成中",
generationProgress: "生成進捗",
favoriteVoice: "声をお気に入り",
recordVoice: "録音",
startRecording: "録音開始",
stopRecording: "録音停止",
recording: "録音中",
recordedVoices: "マイ録音",
noRecordings: "録音はまだありません。録音するとナレーショントラックに追加されます。",
recordingReady: "録音をナレーショントラックに追加しました",
recordingUnsupported: "このブラウザは録音に対応していません",
recordingPermissionDenied: "マイクにアクセスできません。ブラウザ権限を確認してください。",
regenerateVoice: "音声を再生成",
imageTrack: "画像",
sourceTrack: "動画原音",
voiceTrack: "ナレーション",
musicTrack: "BGM",
dropVisualHere: "画像トラックにドロップ",
dropVoiceHere: "ナレーショントラックにドロップ",
dropSourceHere: "原音を分離",
dropMusicHere: "BGMトラックにドロップ",
},
};
Object.assign(UI_COPY, {
ko: {
...UI_COPY.en,
languageTitle: "인터페이스 언어 선택",
languageSubtitle: "한 번 저장하면 다음부터 이 언어로 열립니다.",
languageSaved: "나중에 설정에서 변경할 수 있습니다",
projectTitle: "AI 더빙 프로젝트",
autosave: "자동 저장됨",
undo: "실행 취소",
redo: "다시 실행",
preview: "미리보기",
pause: "일시정지",
play: "재생",
exporting: "내보내는 중",
exportMp4: "MP4 내보내기",
settings: "설정",
media: "미디어",
text: "텍스트",
caption: "자막",
audio: "오디오",
transition: "전환",
effects: "효과",
stickers: "스티커",
filters: "필터",
uploadTab: "업로드",
libraryTab: "라이브러리",
mineTab: "내 자료",
previewEmptyTitle: "이미지나 비디오를 업로드하여 시작",
previewEmptySubtitle: "타임라인은 기본적으로 비어 있습니다",
aiVoice: "AI 음성",
voiceSynthesis: "음성 합성",
myVoices: "내 음성",
history: "기록",
inputScript: "스크립트",
chooseVoice: "음성 선택",
generateVoice: "음성 생성",
regenerateVoice: "음성 다시 생성",
imageTrack: "이미지",
sourceTrack: "원본 오디오",
voiceTrack: "더빙 오디오",
musicTrack: "배경 음악",
},
es: {
...UI_COPY.en,
languageTitle: "Elige el idioma",
languageSubtitle: "Se guarda una vez y se abrirá así la próxima vez.",
languageSaved: "Puedes cambiarlo luego en Ajustes",
projectTitle: "Proyecto de voz con IA",
autosave: "Guardado automático",
undo: "Deshacer",
redo: "Rehacer",
preview: "Vista previa",
pause: "Pausar",
play: "Reproducir",
exporting: "Exportando",
exportMp4: "Exportar MP4",
settings: "Ajustes",
media: "Medios",
text: "Texto",
caption: "Subtítulos",
audio: "Audio",
transition: "Transiciones",
effects: "Efectos",
stickers: "Stickers",
filters: "Filtros",
uploadTab: "Subir",
libraryTab: "Biblioteca",
mineTab: "Mis recursos",
previewEmptyTitle: "Sube una imagen o video para empezar",
previewEmptySubtitle: "La línea de tiempo empieza vacía",
aiVoice: "Voz IA",
voiceSynthesis: "Síntesis de voz",
myVoices: "Mis voces",
history: "Historial",
inputScript: "Guion",
chooseVoice: "Elegir voz",
generateVoice: "Generar voz",
regenerateVoice: "Regenerar voz",
imageTrack: "Imagen",
sourceTrack: "Audio original",
voiceTrack: "Narración",
musicTrack: "Música",
},
fr: {
...UI_COPY.en,
languageTitle: "Choisir la langue",
languageSubtitle: "Enregistrée une fois, elle sera utilisée à la prochaine ouverture.",
languageSaved: "Modifiable plus tard dans les réglages",
projectTitle: "Projet voix IA",
autosave: "Enregistré automatiquement",
undo: "Annuler",
redo: "Rétablir",
preview: "Aperçu",
pause: "Pause",
play: "Lire",
exporting: "Exportation",
exportMp4: "Exporter MP4",
settings: "Réglages",
media: "Médias",
text: "Texte",
caption: "Sous-titres",
audio: "Audio",
transition: "Transitions",
effects: "Effets",
stickers: "Stickers",
filters: "Filtres",
uploadTab: "Importer",
libraryTab: "Bibliothèque",
mineTab: "Mes assets",
previewEmptyTitle: "Importez une image ou vidéo pour commencer",
previewEmptySubtitle: "La timeline démarre vide",
aiVoice: "Voix IA",
voiceSynthesis: "Synthèse vocale",
myVoices: "Mes voix",
history: "Historique",
inputScript: "Script",
chooseVoice: "Choisir une voix",
generateVoice: "Générer la voix",
regenerateVoice: "Regénérer la voix",
imageTrack: "Image",
sourceTrack: "Audio source",
voiceTrack: "Voix off",
musicTrack: "Musique",
},
de: {
...UI_COPY.en,
languageTitle: "Sprache wählen",
languageSubtitle: "Einmal gespeichert, startet der Editor künftig in dieser Sprache.",
languageSaved: "Später in den Einstellungen änderbar",
projectTitle: "AI-Voiceover-Projekt",
autosave: "Automatisch gespeichert",
undo: "Rückgängig",
redo: "Wiederholen",
preview: "Vorschau",
pause: "Pause",
play: "Abspielen",
exporting: "Export läuft",
exportMp4: "MP4 exportieren",
settings: "Einstellungen",
media: "Medien",
text: "Text",
caption: "Untertitel",
audio: "Audio",
transition: "Übergänge",
effects: "Effekte",
stickers: "Sticker",
filters: "Filter",
uploadTab: "Upload",
libraryTab: "Bibliothek",
mineTab: "Meine Medien",
previewEmptyTitle: "Bild oder Video hochladen und starten",
previewEmptySubtitle: "Die Timeline ist standardmäßig leer",
aiVoice: "AI-Stimme",
voiceSynthesis: "Sprachsynthese",
myVoices: "Meine Stimmen",
history: "Verlauf",
inputScript: "Skript",
chooseVoice: "Stimme wählen",
generateVoice: "Stimme erzeugen",
regenerateVoice: "Stimme neu erzeugen",
imageTrack: "Bild",
sourceTrack: "Originalton",
voiceTrack: "Voiceover",
musicTrack: "Musik",
},
pt: {
...UI_COPY.en,
languageTitle: "Escolha o idioma",
languageSubtitle: "Salvo uma vez, o editor abrirá nesse idioma depois.",
languageSaved: "Você pode alterar em Configurações",
projectTitle: "Projeto de voz IA",
autosave: "Salvo automaticamente",
undo: "Desfazer",
redo: "Refazer",
preview: "Prévia",
pause: "Pausar",
play: "Reproduzir",
exporting: "Exportando",
exportMp4: "Exportar MP4",
settings: "Configurações",
media: "Mídia",
text: "Texto",
caption: "Legendas",
audio: "Áudio",
transition: "Transições",
effects: "Efeitos",
stickers: "Stickers",
filters: "Filtros",
uploadTab: "Enviar",
libraryTab: "Biblioteca",
mineTab: "Meus assets",
previewEmptyTitle: "Envie imagem ou vídeo para começar",
previewEmptySubtitle: "A timeline começa vazia",
aiVoice: "Voz IA",
voiceSynthesis: "Síntese de voz",
myVoices: "Minhas vozes",
history: "Histórico",
inputScript: "Roteiro",
chooseVoice: "Escolher voz",
generateVoice: "Gerar voz",
regenerateVoice: "Gerar voz novamente",
imageTrack: "Imagem",
sourceTrack: "Áudio original",
voiceTrack: "Narração",
musicTrack: "Música",
},
th: {
...UI_COPY.en,
languageTitle: "เลือกภาษาอินเทอร์เฟซ",
languageSubtitle: "บันทึกครั้งเดียว ครั้งถัดไปจะเปิดด้วยภาษานี้",
languageSaved: "เปลี่ยนได้ภายหลังใน Settings",
projectTitle: "โปรเจกต์เสียง AI",
autosave: "บันทึกอัตโนมัติ",
undo: "ย้อนกลับ",
redo: "ทำซ้ำ",
preview: "พรีวิว",
pause: "หยุดชั่วคราว",
play: "เล่น",
exporting: "กำลังส่งออก",
exportMp4: "ส่งออก MP4",
settings: "ตั้งค่า",
media: "สื่อ",
text: "ข้อความ",
caption: "คำบรรยาย",
audio: "เสียง",
transition: "ทรานซิชัน",
effects: "เอฟเฟกต์",
stickers: "สติกเกอร์",
filters: "ฟิลเตอร์",
uploadTab: "อัปโหลด",
libraryTab: "คลัง",
mineTab: "สื่อของฉัน",
previewEmptyTitle: "อัปโหลดรูปหรือวิดีโอเพื่อเริ่ม",
previewEmptySubtitle: "ไทม์ไลน์เริ่มต้นว่าง",
aiVoice: "เสียง AI",
voiceSynthesis: "สังเคราะห์เสียง",
myVoices: "เสียงของฉัน",
history: "ประวัติ",
inputScript: "สคริปต์",
chooseVoice: "เลือกเสียง",
generateVoice: "สร้างเสียง",
regenerateVoice: "สร้างเสียงใหม่",
imageTrack: "รูปภาพ",
sourceTrack: "เสียงต้นฉบับ",
voiceTrack: "เสียงพากย์",
musicTrack: "เพลง",
},
vi: {
...UI_COPY.en,
languageTitle: "Chọn ngôn ngữ giao diện",
languageSubtitle: "Lưu một lần, lần sau sẽ mở bằng ngôn ngữ này.",
languageSaved: "Có thể đổi lại trong Cài đặt",
projectTitle: "Dự án lồng tiếng AI",
autosave: "Đã tự lưu",
undo: "Hoàn tác",
redo: "Làm lại",
preview: "Xem trước",
pause: "Tạm dừng",
play: "Phát",
exporting: "Đang xuất",
exportMp4: "Xuất MP4",
settings: "Cài đặt",
media: "Media",
text: "Văn bản",
caption: "Phụ đề",
audio: "Âm thanh",
transition: "Chuyển cảnh",
effects: "Hiệu ứng",
stickers: "Sticker",
filters: "Bộ lọc",
uploadTab: "Tải lên",
libraryTab: "Thư viện",
mineTab: "Tài nguyên của tôi",
previewEmptyTitle: "Tải ảnh hoặc video để bắt đầu",
previewEmptySubtitle: "Timeline mặc định đang trống",
aiVoice: "Giọng AI",
voiceSynthesis: "Tổng hợp giọng nói",
myVoices: "Giọng của tôi",
history: "Lịch sử",
inputScript: "Kịch bản",
chooseVoice: "Chọn giọng",
generateVoice: "Tạo giọng",
regenerateVoice: "Tạo lại giọng",
imageTrack: "Hình ảnh",
sourceTrack: "Âm thanh gốc",
voiceTrack: "Lồng tiếng",
musicTrack: "Nhạc nền",
},
});
export const OPTION_COPY = {
en: {
"原片": "Original",
"冷调清透": "Cool clean",
"胶片暗角": "Film vignette",
"轻亮人像": "Bright portrait",
"清晰增强": "Clarity",
"柔光": "Soft glow",
"电影感": "Cinematic",
"高饱和": "Vivid",
"夜景": "Night",
"暖调": "Warm",
"冷蓝": "Cool blue",
"黑白": "Mono",
"梦幻": "Dream",
"无转场": "None",
"淡入淡出": "Fade",
"轻推拉": "Subtle zoom",
"闪白切换": "Flash",
"左推入": "Push left",
"上推入": "Push up",
"模糊切": "Blur cut",
"双开门": "Split open",
"故障闪": "Glitch",
"无贴纸": "No sticker",
"新品感": "New",
"热点": "Hot",
"旁白": "Voiceover",
},
ja: {
"原片": "オリジナル",
"冷调清透": "クール",
"胶片暗角": "フィルム",
"轻亮人像": "明るい人物",
"清晰增强": "鮮明",
"柔光": "ソフト",
"电影感": "シネマ",
"高饱和": "ビビッド",
"夜景": "夜景",
"暖调": "ウォーム",
"冷蓝": "クールブルー",
"黑白": "モノクロ",
"梦幻": "ドリーム",
"无转场": "なし",
"淡入淡出": "フェード",
"轻推拉": "ズーム",
"闪白切换": "フラッシュ",
"左推入": "左プッシュ",
"上推入": "上プッシュ",
"模糊切": "ぼかし",
"双开门": "スプリット",
"故障闪": "グリッチ",
"无贴纸": "なし",
"新品感": "New",
"热点": "Hot",
"旁白": "Voiceover",
},
};
export const LANGUAGE_FALLBACKS = {
ko: "en",
es: "en",
fr: "en",
de: "en",
pt: "en",
th: "en",
vi: "en",
};
export function getStoredLanguage() {
if (typeof window === "undefined") {
return "";
}
try {
const stored = window.localStorage.getItem(LANGUAGE_STORAGE_KEY);
return APP_LANGUAGES.some((language) => language.id === stored) ? stored : "";
} catch {
return "";
}
}
export function getCopyLanguage(languageId) {
return UI_COPY[languageId] ? languageId : LANGUAGE_FALLBACKS[languageId] ?? "en";
}
export function createTranslator(languageId) {
const copyLanguage = getCopyLanguage(languageId);
const copy = UI_COPY[copyLanguage] ?? UI_COPY.en;
const fallback = UI_COPY.en;
return (key, fallbackText) => copy[key] ?? fallback[key] ?? UI_COPY.zh[key] ?? fallbackText ?? key;
}
export function translateOptionName(languageId, name) {
const copyLanguage = getCopyLanguage(languageId);
return OPTION_COPY[copyLanguage]?.[name] ?? OPTION_COPY.en?.[name] ?? name;
}
export function saveLanguagePreference(languageId) {
try {
window.localStorage.setItem(LANGUAGE_STORAGE_KEY, languageId);
} catch {
// localStorage may be unavailable in private browsing; keep the in-memory language.
}
}
+555
View File
@@ -0,0 +1,555 @@
import {
AUDIO_RECORDING_FORMATS,
EXPORT_RECORDING_FORMATS,
FFMPEG_CLASS_WORKER_URL,
FFMPEG_CORE_BASE_URL,
} from "../config/editor.js";
import {
createCaptionSegments,
getSegmentIndexAtTime,
getVisualSegmentIndexAtTime,
getVisualSegmentTimeline,
makeId,
} from "./timeline.js";
export function getAudioRecordingFormat() {
if (typeof MediaRecorder === "undefined") {
return null;
}
return (
AUDIO_RECORDING_FORMATS.find((format) => MediaRecorder.isTypeSupported(format.mimeType)) ?? {
mimeType: "",
extension: "webm",
}
);
}
let ffmpegLoadPromise = null;
let ffmpegTaskQueue = Promise.resolve();
export async function decodeWaveform(blob, barCount = 118) {
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
if (!AudioContextClass) {
return { duration: 0, peaks: [] };
}
const audioContext = new AudioContextClass();
try {
const buffer = await blob.arrayBuffer();
const decoded = await audioContext.decodeAudioData(buffer.slice(0));
const channelData = decoded.getChannelData(0);
const blockSize = Math.max(1, Math.floor(channelData.length / barCount));
const peaks = Array.from({ length: barCount }, (_, index) => {
const start = index * blockSize;
let peak = 0;
let sumSquares = 0;
let samples = 0;
for (
let cursor = start;
cursor < start + blockSize && cursor < channelData.length;
cursor += 1
) {
const value = Math.abs(channelData[cursor]);
peak = Math.max(peak, value);
sumSquares += value * value;
samples += 1;
}
const rms = samples ? Math.sqrt(sumSquares / samples) : 0;
return rms * 0.78 + peak * 0.22;
});
const strongest = Math.max(...peaks, 0.001);
return {
duration: decoded.duration,
peaks: peaks.map((peak) => Math.max(0.04, Math.min(1, Math.pow(peak / strongest, 0.72)))),
};
} finally {
await audioContext.close().catch(() => {});
}
}
export function downloadBlob(blob, filename) {
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = filename;
anchor.click();
window.setTimeout(() => URL.revokeObjectURL(url), 800);
}
function loadImage(src) {
return new Promise((resolve, reject) => {
const image = new Image();
image.crossOrigin = "anonymous";
image.onload = () => resolve(image);
image.onerror = reject;
image.src = src;
});
}
function loadVideo(src) {
return new Promise((resolve, reject) => {
const video = document.createElement("video");
video.crossOrigin = "anonymous";
video.muted = true;
video.playsInline = true;
video.preload = "auto";
video.onloadedmetadata = () => resolve(video);
video.onerror = reject;
video.src = src;
});
}
function getVisualDimensions(visual) {
return {
width: visual.videoWidth || visual.naturalWidth || 1,
height: visual.videoHeight || visual.naturalHeight || 1,
};
}
function drawFittedVisual(context, visual, canvas, fitMode, filter) {
const { width, height } = canvas;
const visualSize = getVisualDimensions(visual);
const imageRatio = visualSize.width / visualSize.height;
const canvasRatio = width / height;
const cover = fitMode === "cover";
let drawWidth;
let drawHeight;
if (cover ? imageRatio > canvasRatio : imageRatio < canvasRatio) {
drawHeight = height;
drawWidth = height * imageRatio;
} else {
drawWidth = width;
drawHeight = width / imageRatio;
}
const x = (width - drawWidth) / 2;
const y = (height - drawHeight) / 2;
context.filter = filter;
context.drawImage(visual, x, y, drawWidth, drawHeight);
context.filter = "none";
}
function drawPreviewFrame(context, visual, canvas, options) {
const {
subtitle,
progress = 0,
fitMode = "contain",
filter = "none",
captionsEnabled = true,
captionPosition = "bottom",
captionPlacement = null,
captionSize = 34,
sticker = null,
transitionId = "none",
} = options;
const { width, height } = canvas;
context.clearRect(0, 0, width, height);
context.fillStyle = "#090b0f";
context.fillRect(0, 0, width, height);
drawFittedVisual(context, visual, canvas, fitMode, filter);
if (captionsEnabled && subtitle) {
const overlayHeight = Math.max(72, captionSize * 2.25);
const yMap = {
top: 48,
middle: height / 2 - overlayHeight / 2,
bottom: height - overlayHeight - 42,
};
const overlayWidth = width - 192;
const overlayX = captionPlacement
? Math.max(24, Math.min(width - overlayWidth - 24, (width * captionPlacement.x) / 100 - overlayWidth / 2))
: 96;
const overlayY = captionPlacement
? Math.max(24, Math.min(height - overlayHeight - 24, (height * captionPlacement.y) / 100 - overlayHeight / 2))
: yMap[captionPosition] ?? yMap.bottom;
context.fillStyle = "rgba(5, 8, 13, 0.62)";
context.fillRect(overlayX, overlayY, overlayWidth, overlayHeight);
context.font = `600 ${captionSize}px Inter, system-ui, sans-serif`;
context.textAlign = "center";
context.fillStyle = "#f5fbff";
context.fillText(subtitle.slice(0, 34), overlayX + overlayWidth / 2, overlayY + overlayHeight * 0.62);
}
if (sticker?.text) {
context.fillStyle = "rgba(53, 240, 221, 0.92)";
context.fillRect(width - 246, 54, 172, 54);
context.fillStyle = "#061515";
context.font = "800 24px Inter, system-ui, sans-serif";
context.textAlign = "center";
context.fillText(sticker.text, width - 160, 90);
}
if (transitionId === "fade") {
const fadeAlpha =
progress < 0.12 ? 1 - progress / 0.12 : progress > 0.88 ? (progress - 0.88) / 0.12 : 0;
if (fadeAlpha > 0) {
context.fillStyle = `rgba(0, 0, 0, ${Math.min(0.72, fadeAlpha * 0.72)})`;
context.fillRect(0, 0, width, height);
}
}
if (transitionId === "flash" && progress < 0.08) {
context.fillStyle = `rgba(255, 255, 255, ${0.45 * (1 - progress / 0.08)})`;
context.fillRect(0, 0, width, height);
}
context.fillStyle = "#35f0dd";
context.fillRect(110, height - 24, (width - 220) * progress, 6);
}
function getSupportedRecordingFormat() {
const supportedFormat = EXPORT_RECORDING_FORMATS.find((format) =>
MediaRecorder.isTypeSupported(format.mimeType),
);
return supportedFormat ?? {
mimeType: "",
extension: "webm",
label: "默认视频",
};
}
function createVideoRecorder(outputStream) {
for (const format of EXPORT_RECORDING_FORMATS) {
if (!MediaRecorder.isTypeSupported(format.mimeType)) {
continue;
}
try {
return {
recorder: new MediaRecorder(outputStream, { mimeType: format.mimeType }),
format,
};
} catch (error) {
console.warn(`MediaRecorder cannot start with ${format.mimeType}`, error);
}
}
return {
recorder: new MediaRecorder(outputStream),
format: {
mimeType: "",
extension: "webm",
label: "默认视频",
},
};
}
export async function exportBrowserVideo({
imageSrc,
visualType,
visualSegments = [],
audioBlob,
voiceVolume = 1,
sourceAudioBlob,
sourceAudioVolume = 1,
musicBlob,
musicVolume = 0.35,
text,
captionSegments,
duration,
ratio,
fitMode,
filter,
captionsEnabled,
captionPosition,
captionPlacement,
captionSize,
sticker,
transitionId,
onProgress,
}) {
if (!window.MediaRecorder) {
throw new Error("当前浏览器不支持 MediaRecorder,无法导出视频。");
}
onProgress?.({ progress: 4, phase: "准备导出画面" });
const exportVisualSegments = visualSegments.some((segment) => segment.src)
? visualSegments.filter((segment) => segment.src)
: [{ id: "export-visual", src: imageSrc, type: visualType, duration }];
const exportVisualTimeline = getVisualSegmentTimeline(exportVisualSegments);
const visualItems = await Promise.all(
exportVisualSegments.map(async (segment) => ({
segment,
visual: segment.type === "video" ? await loadVideo(segment.src) : await loadImage(segment.src),
})),
);
onProgress?.({ progress: 8, phase: "准备画布与轨道" });
const canvas = document.createElement("canvas");
canvas.width = ratio.width;
canvas.height = ratio.height;
const context = canvas.getContext("2d");
const canvasStream = canvas.captureStream(30);
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
let audioContext = null;
let decodedDuration = 0;
const sources = [];
let destination = null;
const audioInputs = [
audioBlob ? { blob: audioBlob, volume: voiceVolume, role: "voice" } : null,
sourceAudioBlob ? { blob: sourceAudioBlob, volume: sourceAudioVolume, role: "source" } : null,
musicBlob ? { blob: musicBlob, volume: musicVolume, role: "music" } : null,
].filter(Boolean);
if (audioInputs.length) {
if (!AudioContextClass) {
throw new Error("当前浏览器不支持 AudioContext,无法混入音频。");
}
onProgress?.({ progress: 12, phase: "解码并混合音频轨" });
audioContext = new AudioContextClass();
destination = audioContext.createMediaStreamDestination();
const decodedInputs = await Promise.all(
audioInputs.map(async (input) => {
const audioBuffer = await input.blob.arrayBuffer();
const decoded = await audioContext.decodeAudioData(audioBuffer.slice(0));
return { ...input, decoded };
}),
);
decodedDuration = decodedInputs.find((input) => input.role === "voice")?.decoded.duration ?? 0;
decodedInputs.forEach((input) => {
const source = audioContext.createBufferSource();
const gain = audioContext.createGain();
source.buffer = input.decoded;
gain.gain.value = input.volume;
source.connect(gain);
gain.connect(destination);
sources.push(source);
});
}
const outputStream = new MediaStream([
...canvasStream.getVideoTracks(),
...(destination ? destination.stream.getAudioTracks() : []),
]);
const { recorder, format: recordingFormat } = createVideoRecorder(outputStream);
const chunks = [];
const exportSegments = captionSegments?.length ? captionSegments : createCaptionSegments(text);
const segments = exportSegments.map((segment) => segment.text);
const totalDuration = Math.max(
duration,
decodedDuration,
...sources.map((source) => source.buffer?.duration ?? 0),
1,
);
const captionTargetDuration = decodedDuration || 0;
recorder.ondataavailable = (event) => {
if (event.data.size > 0) {
chunks.push(event.data);
}
};
const stopped = new Promise((resolve) => {
recorder.onstop = () => resolve();
});
onProgress?.({ progress: 16, phase: "开始录制视频流" });
recorder.start(250);
const singleVideo =
visualItems.length === 1 && visualItems[0]?.segment.type === "video"
? visualItems[0].visual
: null;
if (singleVideo) {
singleVideo.currentTime = 0;
singleVideo.loop = totalDuration > (singleVideo.duration || totalDuration);
await singleVideo.play().catch(() => {});
}
const startTime = performance.now();
let animationFrame = 0;
let lastProgressUpdate = 0;
const getVisualItemAtTime = (elapsed) => {
const visualIndex = getVisualSegmentIndexAtTime(exportVisualSegments, elapsed);
return {
item: visualItems[Math.max(0, visualIndex)] ?? visualItems[0],
range: exportVisualTimeline[Math.max(0, visualIndex)] ?? exportVisualTimeline[0],
};
};
const draw = () => {
const elapsed = Math.min(totalDuration, (performance.now() - startTime) / 1000);
const segmentIndex = getSegmentIndexAtTime(exportSegments, elapsed, captionTargetDuration);
const exportCaption =
segmentIndex >= 0 && !exportSegments[segmentIndex]?.hidden ? segments[segmentIndex] : "";
const { item: visualItem, range: visualRange } = getVisualItemAtTime(elapsed);
if (visualItem?.segment.type === "video" && !singleVideo) {
const localTime = Math.max(0, elapsed - (visualRange?.start ?? 0));
const nextVideoTime = Math.min(localTime, visualItem.visual.duration || localTime);
if (Math.abs(visualItem.visual.currentTime - nextVideoTime) > 0.18) {
visualItem.visual.currentTime = nextVideoTime;
}
}
drawPreviewFrame(context, visualItem.visual, canvas, {
subtitle: exportCaption,
progress: elapsed / totalDuration,
fitMode,
filter,
captionsEnabled,
captionPosition,
captionPlacement,
captionSize,
sticker,
transitionId,
});
if (elapsed === totalDuration || performance.now() - lastProgressUpdate > 180) {
lastProgressUpdate = performance.now();
onProgress?.({
progress: Math.min(92, 16 + Math.round((elapsed / totalDuration) * 76)),
phase: "录制视频流",
});
}
if (elapsed < totalDuration) {
animationFrame = requestAnimationFrame(draw);
}
};
draw();
sources.forEach((source) => source.start());
await new Promise((resolve) => {
window.setTimeout(resolve, totalDuration * 1000);
});
cancelAnimationFrame(animationFrame);
visualItems.forEach((item) => {
if (item.segment.type === "video") {
item.visual.pause();
}
});
const finalSegmentIndex = getSegmentIndexAtTime(exportSegments, totalDuration, captionTargetDuration);
const { item: finalVisualItem } = getVisualItemAtTime(totalDuration);
drawPreviewFrame(context, finalVisualItem.visual, canvas, {
subtitle:
finalSegmentIndex >= 0 && !exportSegments[finalSegmentIndex]?.hidden
? segments[finalSegmentIndex]
: "",
progress: 1,
fitMode,
filter,
captionsEnabled,
captionPosition,
captionPlacement,
captionSize,
sticker,
transitionId,
});
recorder.stop();
onProgress?.({ progress: 94, phase: "封装导出文件" });
await stopped;
canvasStream.getTracks().forEach((track) => track.stop());
destination?.stream.getTracks().forEach((track) => track.stop());
await audioContext?.close().catch(() => {});
const blobType = recorder.mimeType || recordingFormat.mimeType || "video/webm";
return {
blob: new Blob(chunks, { type: blobType }),
extension: recordingFormat.extension,
label: recordingFormat.label,
mimeType: blobType,
nativeMp4: recordingFormat.extension === "mp4",
};
}
async function getFfmpeg() {
if (!ffmpegLoadPromise) {
ffmpegLoadPromise = (async () => {
const [{ FFmpeg }, { toBlobURL }] = await Promise.all([
import("@ffmpeg/ffmpeg"),
import("@ffmpeg/util"),
]);
const ffmpeg = new FFmpeg();
const classWorkerURL = URL.createObjectURL(
new Blob([`import "${FFMPEG_CLASS_WORKER_URL}";`], { type: "text/javascript" }),
);
await ffmpeg.load({
classWorkerURL,
coreURL: await toBlobURL(`${FFMPEG_CORE_BASE_URL}/ffmpeg-core.js`, "text/javascript"),
wasmURL: await toBlobURL(`${FFMPEG_CORE_BASE_URL}/ffmpeg-core.wasm`, "application/wasm"),
});
return ffmpeg;
})();
}
return ffmpegLoadPromise;
}
function runFfmpegTask(task) {
const nextTask = ffmpegTaskQueue.catch(() => {}).then(task);
ffmpegTaskQueue = nextTask.catch(() => {});
return nextTask;
}
export async function transcodeWebmToMp4(webmBlob) {
return runFfmpegTask(async () => {
const [{ fetchFile }, ffmpeg] = await Promise.all([import("@ffmpeg/util"), getFfmpeg()]);
const id = makeId("export");
const inputName = `${id}.webm`;
const outputName = `${id}.mp4`;
await ffmpeg.writeFile(inputName, await fetchFile(webmBlob));
try {
await ffmpeg.exec([
"-i",
inputName,
"-c:v",
"libx264",
"-preset",
"veryfast",
"-pix_fmt",
"yuv420p",
"-c:a",
"aac",
"-movflags",
"faststart",
outputName,
]);
} catch (error) {
await ffmpeg.deleteFile(outputName).catch(() => {});
await ffmpeg.exec(["-i", inputName, "-movflags", "faststart", outputName]);
}
const data = await ffmpeg.readFile(outputName);
await ffmpeg.deleteFile(inputName).catch(() => {});
await ffmpeg.deleteFile(outputName).catch(() => {});
return new Blob([data], { type: "video/mp4" });
});
}
export async function extractAudioFromVideo(videoBlob, filename = "source-video.mp4") {
return runFfmpegTask(async () => {
const [{ fetchFile }, ffmpeg] = await Promise.all([import("@ffmpeg/util"), getFfmpeg()]);
const id = makeId("source-audio");
const extension = filename.split(".").pop()?.toLowerCase().replace(/[^a-z0-9]/g, "") || "mp4";
const inputName = `${id}.${extension}`;
const outputName = `${id}.wav`;
await ffmpeg.writeFile(inputName, await fetchFile(videoBlob));
try {
await ffmpeg.exec([
"-i",
inputName,
"-vn",
"-ac",
"2",
"-ar",
"44100",
"-f",
"wav",
outputName,
]);
const data = await ffmpeg.readFile(outputName);
return new Blob([data], { type: "audio/wav" });
} finally {
await ffmpeg.deleteFile(inputName).catch(() => {});
await ffmpeg.deleteFile(outputName).catch(() => {});
}
});
}
+213
View File
@@ -0,0 +1,213 @@
import {
MAX_CAPTION_SEGMENT_SECONDS,
MAX_IMAGE_THUMBNAILS,
MAX_TIMELINE_DURATION_SECONDS,
MIN_CAPTION_SEGMENT_SECONDS,
MIN_VISUAL_SEGMENT_SECONDS,
IMAGE_SEGMENT_SECONDS,
} from "../config/editor.js";
export function makeId(prefix) {
return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
}
export function getImageThumbnailCount(duration) {
return Math.min(
MAX_IMAGE_THUMBNAILS,
Math.max(1, Math.ceil(duration / IMAGE_SEGMENT_SECONDS)),
);
}
export function getVisualAssetPayload(asset) {
if (!asset) {
return {};
}
return {
assetId: asset.assetId ?? asset.id ?? "",
type: asset.type ?? "image",
src: asset.src ?? "",
name: asset.name ?? "",
meta: asset.meta ?? "",
blob: asset.blob ?? null,
};
}
export function createVisualSegment(duration = 4, asset = null) {
return {
id: makeId("visual"),
duration: Math.max(MIN_VISUAL_SEGMENT_SECONDS, Math.min(MAX_TIMELINE_DURATION_SECONDS, duration)),
...getVisualAssetPayload(asset),
};
}
export function getVisualSegmentsTotal(segments) {
return segments.reduce((sum, segment) => sum + Math.max(0, segment.duration || 0), 0);
}
export function reorderTimelineItems(items, fromIndex, toIndex) {
if (
fromIndex === toIndex ||
fromIndex < 0 ||
toIndex < 0 ||
fromIndex >= items.length ||
toIndex >= items.length
) {
return items;
}
const nextItems = [...items];
const [movedItem] = nextItems.splice(fromIndex, 1);
nextItems.splice(toIndex, 0, movedItem);
return nextItems;
}
export function getVisualSegmentTimeline(segments) {
let cursor = 0;
return segments.map((segment) => {
const duration = Math.max(0, segment.duration || 0);
const item = {
id: segment.id,
start: cursor,
end: cursor + duration,
duration,
};
cursor += duration;
return item;
});
}
export function getVisualSegmentIndexAtTime(segments, time) {
if (!segments.length) {
return -1;
}
const timeline = getVisualSegmentTimeline(segments);
const clampedTime = Math.max(0, Math.min(getVisualSegmentsTotal(segments), time));
const index = timeline.findIndex(
(segment) => clampedTime >= segment.start && clampedTime < segment.end,
);
return index >= 0 ? index : timeline.length - 1;
}
export function getCaptionDefaultWeight(text) {
const compact = text.replace(/\s/g, "");
return Math.max(1, Math.min(4, Math.ceil(compact.length / 14)));
}
export function getCaptionBaseDuration(text) {
const compact = text.replace(/\s/g, "");
if (!compact) {
return MIN_CAPTION_SEGMENT_SECONDS;
}
return Math.max(
MIN_CAPTION_SEGMENT_SECONDS,
Math.min(MAX_CAPTION_SEGMENT_SECONDS, compact.length / 4.2 + 0.45),
);
}
export function getCaptionSegmentDuration(segment) {
const defaultWeight = getCaptionDefaultWeight(segment.text);
const weight = Number.isFinite(segment.weight) ? segment.weight : defaultWeight;
const weightScale = Math.max(0.35, weight / defaultWeight);
return getCaptionBaseDuration(segment.text) * weightScale;
}
export function getCaptionTimeline(captionSegments, targetDuration = 0) {
const naturalDurations = captionSegments.map((segment) => getCaptionSegmentDuration(segment));
const naturalTotal = naturalDurations.reduce((sum, duration) => sum + duration, 0);
const shouldAlignToTarget = targetDuration > 0 && naturalTotal > 0;
const scale = shouldAlignToTarget ? targetDuration / naturalTotal : 1;
let cursor = 0;
return captionSegments.map((segment, index) => {
const duration = naturalDurations[index] * scale;
const timelineItem = {
start: cursor,
end: cursor + duration,
duration,
};
cursor += duration;
return timelineItem;
});
}
export function createCaptionSegments(text) {
return getScriptSegments(text).map((segment) => ({
id: makeId("caption"),
text: segment,
weight: getCaptionDefaultWeight(segment),
hidden: false,
}));
}
export function getCaptionScript(segments) {
return segments.map((segment) => segment.text).join("\n");
}
export function getSegmentIndexAtTime(captionSegments, currentTime, targetDuration = 0) {
if (!captionSegments.length) {
return -1;
}
const timeline = getCaptionTimeline(captionSegments, targetDuration);
const time = Math.max(0, currentTime);
for (let index = 0; index < timeline.length; index += 1) {
if (time >= timeline[index].start && time <= timeline[index].end) {
return index;
}
}
return -1;
}
export function getSegmentStartTime(captionSegments, index, targetDuration = 0) {
return getCaptionTimeline(captionSegments, targetDuration)[Math.max(0, index)]?.start ?? 0;
}
export function formatTime(value) {
const seconds = Math.max(0, Number.isFinite(value) ? value : 0);
const minutes = Math.floor(seconds / 60);
const wholeSeconds = Math.floor(seconds % 60);
const centiseconds = Math.floor((seconds % 1) * 100);
return `${String(minutes).padStart(2, "0")}:${String(wholeSeconds).padStart(
2,
"0",
)}.${String(centiseconds).padStart(2, "0")}`;
}
export function formatClock(value) {
const seconds = Math.max(0, Number.isFinite(value) ? value : 0);
const minutes = Math.floor(seconds / 60);
const wholeSeconds = Math.floor(seconds % 60);
return `${String(minutes).padStart(2, "0")}:${String(wholeSeconds).padStart(2, "0")}`;
}
export function getScriptSegments(text) {
const cleaned = text
.split(/[\n。!?!?]+/)
.map((item) => item.trim())
.filter(Boolean);
if (cleaned.length) {
return cleaned.slice(0, 8);
}
return [];
}
export function estimateDuration(text) {
const segments = getScriptSegments(text);
if (!segments.length) {
return 0;
}
return Math.min(45, segments.reduce((sum, segment) => sum + getCaptionBaseDuration(segment), 0));
}
export function formatSavedTime(date = new Date()) {
return date.toLocaleTimeString("zh-CN", {
hour12: false,
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
});
}
+10
View File
@@ -0,0 +1,10 @@
import React from "react";
import { createRoot } from "react-dom/client";
import { App } from "./App.jsx";
import "./styles.css";
createRoot(document.getElementById("root")).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
+2987
View File
File diff suppressed because it is too large. Load diff
+14
View File
@@ -0,0 +1,14 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
optimizeDeps: {
include: ["react", "react-dom/client"],
},
server: {
warmup: {
clientFiles: ["./src/main.jsx"],
},
},
plugins: [react()],
});