feat: add expandable multi-track voiceover timeline
This commit is contained in:
1 parent
e302b25288
commit
6f0666e513
10 files changed
+608
-145
No files matched your search
+273
-80
@@ -3,6 +3,7 @@ import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
ASSET_DRAG_MIME,
|
||||
DEFAULT_STICKER_SEGMENT_SECONDS,
|
||||
DEFAULT_TIMELINE_DURATION_SECONDS,
|
||||
DEFAULT_SCRIPT,
|
||||
FILTER_OPTIONS,
|
||||
IMAGE_RESIZE_OVERFLOW_SECONDS_PER_PIXEL,
|
||||
@@ -59,6 +60,7 @@ import {
|
||||
extractAudioFromVideo,
|
||||
getAudioRecordingFormat,
|
||||
getSupportedRecordingFormat,
|
||||
reverseAudioBlob,
|
||||
transcodeWebmToMp4,
|
||||
} from "./lib/media.js";
|
||||
import { createProjectArchive, readProjectArchive, readProjectFileAsText } from "./lib/projectArchive.js";
|
||||
@@ -99,6 +101,16 @@ const EMPTY_VISION_OPTIONS = Object.freeze({
|
||||
smartCrop: false,
|
||||
});
|
||||
|
||||
function getAudioSegmentPreviewVolume(segment, timelineTime) {
|
||||
const volume = Math.max(0, Math.min(1, segment.volume ?? 1));
|
||||
const localTime = Math.max(0, Math.min(segment.duration, timelineTime - segment.start));
|
||||
const fadeIn = Math.max(0, Math.min(segment.duration, segment.fadeIn || 0));
|
||||
const fadeOut = Math.max(0, Math.min(segment.duration, segment.fadeOut || 0));
|
||||
const fadeInGain = fadeIn > 0 ? Math.min(1, localTime / fadeIn) : 1;
|
||||
const fadeOutGain = fadeOut > 0 ? Math.min(1, (segment.duration - localTime) / fadeOut) : 1;
|
||||
return volume * Math.max(0, Math.min(fadeInGain, fadeOutGain));
|
||||
}
|
||||
|
||||
async function decodeAvatarAudio16k(blob) {
|
||||
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
|
||||
if (!AudioContextClass) throw new Error("当前浏览器不支持音频解码");
|
||||
@@ -268,10 +280,9 @@ export function App() {
|
||||
const [imageName, setImageName] = useState("");
|
||||
const [imageMeta, setImageMeta] = useState("");
|
||||
const [visualType, setVisualType] = useState("image");
|
||||
const [audioBlob, setAudioBlob] = useState(null);
|
||||
const [audioUrl, setAudioUrl] = useState("");
|
||||
const [audioDuration, setAudioDuration] = useState(estimateDuration(DEFAULT_SCRIPT));
|
||||
const [peaks, setPeaks] = useState([]);
|
||||
const [audioSegments, setAudioSegments] = useState([]);
|
||||
const [selectedAudioSegmentId, setSelectedAudioSegmentId] = useState("");
|
||||
const [timelineHorizon, setTimelineHorizon] = useState(DEFAULT_TIMELINE_DURATION_SECONDS);
|
||||
const [musicBlob, setMusicBlob] = useState(null);
|
||||
const [musicUrl, setMusicUrl] = useState("");
|
||||
const [musicName, setMusicName] = useState("");
|
||||
@@ -313,7 +324,7 @@ export function App() {
|
||||
const [showFileMenu, setShowFileMenu] = useState(false);
|
||||
const [compactRail, setCompactRail] = useState(false);
|
||||
const [selectedTrack, setSelectedTrack] = useState("image");
|
||||
const [timelineZoom, setTimelineZoom] = useState(1);
|
||||
const [timelineZoom, setTimelineZoom] = useState(0.25);
|
||||
const [trackVisibility, setTrackVisibility] = useState({
|
||||
image: true,
|
||||
caption: true,
|
||||
@@ -375,6 +386,7 @@ export function App() {
|
||||
const previewShellRef = useRef(null);
|
||||
const previewCanvasRef = useRef(null);
|
||||
const audioRef = useRef(null);
|
||||
const audioSegmentRefs = useRef(new Map());
|
||||
const sourceAudioRef = useRef(null);
|
||||
const musicRef = useRef(null);
|
||||
const previewVideoRef = useRef(null);
|
||||
@@ -430,6 +442,12 @@ export function App() {
|
||||
() => VOICES.find((voice) => voice.id === selectedVoiceId) ?? VOICES[0],
|
||||
[selectedVoiceId],
|
||||
);
|
||||
const selectedAudioSegment =
|
||||
audioSegments.find((segment) => segment.id === selectedAudioSegmentId) ?? audioSegments.at(-1) ?? null;
|
||||
const audioBlob = selectedAudioSegment?.blob ?? null;
|
||||
const audioUrl = selectedAudioSegment?.url ?? "";
|
||||
const audioDuration = selectedAudioSegment?.duration ?? 0;
|
||||
const peaks = selectedAudioSegment?.peaks ?? [];
|
||||
|
||||
function openAvatarPanel() {
|
||||
setAvatarPanelOpen(true);
|
||||
@@ -575,7 +593,8 @@ export function App() {
|
||||
: null;
|
||||
|
||||
const segments = useMemo(() => captionSegments.map((segment) => segment.text), [captionSegments]);
|
||||
const captionTargetDuration = audioBlob ? audioDuration : 0;
|
||||
const voiceTrackDuration = useMemo(() => getTimedSegmentsEnd(audioSegments), [audioSegments]);
|
||||
const captionTargetDuration = voiceTrackDuration;
|
||||
const captionTimeline = useMemo(
|
||||
() => getCaptionTimeline(captionSegments, captionTargetDuration),
|
||||
[captionSegments, captionTargetDuration],
|
||||
@@ -586,7 +605,7 @@ export function App() {
|
||||
const estimatedDuration = useMemo(
|
||||
() =>
|
||||
Math.max(
|
||||
audioBlob ? audioDuration : 0,
|
||||
voiceTrackDuration,
|
||||
captionDuration,
|
||||
sourceAudioBlob ? sourceAudioStart + sourceAudioDuration : 0,
|
||||
musicBlob ? musicDuration : 0,
|
||||
@@ -595,8 +614,7 @@ export function App() {
|
||||
imageSrc ? imageDuration : 0,
|
||||
),
|
||||
[
|
||||
audioBlob,
|
||||
audioDuration,
|
||||
voiceTrackDuration,
|
||||
captionDuration,
|
||||
imageDuration,
|
||||
imageSrc,
|
||||
@@ -611,13 +629,11 @@ export function App() {
|
||||
);
|
||||
const timelineDuration = useMemo(
|
||||
() =>
|
||||
estimatedDuration > 0
|
||||
? Math.min(
|
||||
MAX_TIMELINE_DURATION_SECONDS,
|
||||
Math.max(10, Math.ceil((estimatedDuration + 1) / 10) * 10),
|
||||
)
|
||||
: 0,
|
||||
[estimatedDuration],
|
||||
Math.min(
|
||||
MAX_TIMELINE_DURATION_SECONDS,
|
||||
Math.max(timelineHorizon, DEFAULT_TIMELINE_DURATION_SECONDS, Math.ceil((estimatedDuration + 1) / 10) * 10),
|
||||
),
|
||||
[estimatedDuration, timelineHorizon],
|
||||
);
|
||||
timelineDurationRef.current = timelineDuration;
|
||||
const currentSegmentIndex = getSegmentIndexAtTime(
|
||||
@@ -957,11 +973,28 @@ export function App() {
|
||||
}, [ratioId, visualSegments]);
|
||||
|
||||
useEffect(() => {
|
||||
if (audioRef.current) {
|
||||
audioRef.current.volume = volume;
|
||||
audioRef.current.playbackRate = speed;
|
||||
}
|
||||
}, [volume, speed, audioUrl]);
|
||||
audioSegments.forEach((segment) => {
|
||||
const audio = audioSegmentRefs.current.get(segment.id);
|
||||
if (!audio) return;
|
||||
audio.volume = getAudioSegmentPreviewVolume(segment, currentTime);
|
||||
});
|
||||
}, [audioSegments, currentTime]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPlaying || !trackVisibility.audio) return;
|
||||
audioSegments.forEach((segment) => {
|
||||
const audio = audioSegmentRefs.current.get(segment.id);
|
||||
if (!audio) return;
|
||||
const active = isTimelineTimeInsideTrack(currentTime, segment.start, segment.duration);
|
||||
if (active) {
|
||||
const expected = getTimelineTrackLocalTime(currentTime, segment.start, segment.duration);
|
||||
if (Math.abs(audio.currentTime - expected) > 0.2) audio.currentTime = expected;
|
||||
if (audio.paused) audio.play().catch(() => {});
|
||||
} else if (!audio.paused) {
|
||||
audio.pause();
|
||||
}
|
||||
});
|
||||
}, [audioSegments, currentTime, isPlaying, trackVisibility.audio]);
|
||||
|
||||
useEffect(() => {
|
||||
if (sourceAudioRef.current) {
|
||||
@@ -1161,7 +1194,7 @@ export function App() {
|
||||
|
||||
useEffect(() => {
|
||||
setCurrentTime((time) => {
|
||||
const clamped = Math.min(time, estimatedDuration);
|
||||
const clamped = Math.min(time, timelineDuration);
|
||||
if (audioRef.current && clamped !== time) {
|
||||
audioRef.current.currentTime = clamped;
|
||||
}
|
||||
@@ -1177,7 +1210,7 @@ export function App() {
|
||||
}
|
||||
return clamped;
|
||||
});
|
||||
}, [estimatedDuration, sourceAudioDuration, sourceAudioStart]);
|
||||
}, [timelineDuration, sourceAudioDuration, sourceAudioStart]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!captionSegments.length) {
|
||||
@@ -1214,6 +1247,7 @@ export function App() {
|
||||
target instanceof HTMLElement &&
|
||||
(target.tagName === "INPUT" ||
|
||||
target.tagName === "TEXTAREA" ||
|
||||
target.tagName === "SELECT" ||
|
||||
target.isContentEditable);
|
||||
|
||||
if (
|
||||
@@ -1227,9 +1261,10 @@ export function App() {
|
||||
}
|
||||
|
||||
const hasSelectedTimelineItem =
|
||||
(selectedTrack === "caption" && captionSegments.length > 0) ||
|
||||
(selectedTrack === "image" && imageSrc && imageClipCount > 0) ||
|
||||
(selectedTrack === "audio" && audioBlob) ||
|
||||
(selectedTrack === "caption" && selectedSegmentId && captionSegments.some((segment) => segment.id === selectedSegmentId)) ||
|
||||
(selectedTrack === "sticker" && selectedStickerSegmentId && stickerSegments.some((segment) => segment.id === selectedStickerSegmentId)) ||
|
||||
(selectedTrack === "image" && selectedVisualSegmentId && visualSegments.some((segment) => segment.id === selectedVisualSegmentId)) ||
|
||||
(selectedTrack === "audio" && selectedAudioSegmentId && audioSegments.some((segment) => segment.id === selectedAudioSegmentId)) ||
|
||||
(selectedTrack === "source" && sourceAudioBlob) ||
|
||||
(selectedTrack === "music" && musicBlob);
|
||||
|
||||
@@ -1758,11 +1793,10 @@ export function App() {
|
||||
function updateScript(nextScript) {
|
||||
pushScriptHistory(script);
|
||||
setScript(nextScript);
|
||||
const nextSegments = createCaptionSegments(nextScript);
|
||||
setCaptionSegments(nextSegments);
|
||||
setSelectedSegmentId(nextSegments[0]?.id ?? "");
|
||||
if (!audioBlob) {
|
||||
setAudioDuration(estimateDuration(nextScript));
|
||||
if (!audioSegments.length) {
|
||||
const nextSegments = createCaptionSegments(nextScript);
|
||||
setCaptionSegments(nextSegments);
|
||||
setSelectedSegmentId(nextSegments[0]?.id ?? "");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1778,9 +1812,6 @@ export function App() {
|
||||
);
|
||||
const nextScript = getCaptionScript(nextSegments);
|
||||
setScript(nextScript);
|
||||
if (!audioBlob) {
|
||||
setAudioDuration(estimateDuration(nextScript));
|
||||
}
|
||||
return nextSegments;
|
||||
});
|
||||
}
|
||||
@@ -1834,7 +1865,6 @@ export function App() {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const disabledSmartAvoidance = Boolean(
|
||||
previewVisionKey && previewVisionRecord?.options?.avoidCaptions,
|
||||
@@ -1902,9 +1932,6 @@ export function App() {
|
||||
? normalized[Math.min(nextSelectedIndex, normalized.length - 1)]?.id ?? ""
|
||||
: "",
|
||||
);
|
||||
if (!audioBlob) {
|
||||
setAudioDuration(estimateDuration(nextScript));
|
||||
}
|
||||
notify(message);
|
||||
}
|
||||
|
||||
@@ -2090,7 +2117,6 @@ export function App() {
|
||||
const previousSegments = createCaptionSegments(previous);
|
||||
setCaptionSegments(previousSegments);
|
||||
setSelectedSegmentId(previousSegments[0]?.id ?? "");
|
||||
setAudioDuration(estimateDuration(previous));
|
||||
notify("已撤销文本修改");
|
||||
return stack.slice(0, -1);
|
||||
});
|
||||
@@ -2108,40 +2134,45 @@ export function App() {
|
||||
const nextSegments = createCaptionSegments(next);
|
||||
setCaptionSegments(nextSegments);
|
||||
setSelectedSegmentId(nextSegments[0]?.id ?? "");
|
||||
setAudioDuration(estimateDuration(next));
|
||||
notify("已重做文本修改");
|
||||
return stack.slice(0, -1);
|
||||
});
|
||||
}
|
||||
|
||||
function replaceAudio(blob, duration, nextPeaks, nextStatusText) {
|
||||
if (audioUrlRef.current) {
|
||||
URL.revokeObjectURL(audioUrlRef.current);
|
||||
}
|
||||
const nextUrl = URL.createObjectURL(blob);
|
||||
audioUrlRef.current = nextUrl;
|
||||
setAudioBlob(blob);
|
||||
setAudioUrl(nextUrl);
|
||||
setAudioDuration(duration || estimateDuration(script));
|
||||
setPeaks(nextPeaks);
|
||||
setCurrentTime(0);
|
||||
const nextDuration = duration || estimateDuration(script);
|
||||
const start = Math.max(0, currentTimeRef.current || 0);
|
||||
const id = crypto.randomUUID();
|
||||
const segment = {
|
||||
id,
|
||||
blob,
|
||||
url: nextUrl,
|
||||
start,
|
||||
duration: nextDuration,
|
||||
peaks: nextPeaks,
|
||||
volume: 1,
|
||||
fadeIn: 0,
|
||||
fadeOut: 0,
|
||||
reversed: false,
|
||||
name: selectedVoice?.name || t("voiceTrack"),
|
||||
};
|
||||
setAudioSegments((segments) => [...segments, segment]);
|
||||
setSelectedAudioSegmentId(id);
|
||||
setSelectedTrack("audio");
|
||||
setTimelineHorizon((value) => Math.max(value, Math.ceil((start + nextDuration + 5) / 10) * 10));
|
||||
setCurrentTime(start);
|
||||
setStatus("done");
|
||||
setStatusText(nextStatusText);
|
||||
setProgress(100);
|
||||
return segment;
|
||||
}
|
||||
|
||||
function clearAudioTrack(message = "配音音频已从时间线移除") {
|
||||
if (audioRef.current) {
|
||||
audioRef.current.pause();
|
||||
}
|
||||
if (audioUrlRef.current) {
|
||||
URL.revokeObjectURL(audioUrlRef.current);
|
||||
audioUrlRef.current = "";
|
||||
}
|
||||
setAudioBlob(null);
|
||||
setAudioUrl("");
|
||||
setPeaks([]);
|
||||
setAudioDuration(estimateDuration(script));
|
||||
audioSegmentRefs.current.forEach((audio) => audio.pause());
|
||||
audioSegments.forEach((segment) => URL.revokeObjectURL(segment.url));
|
||||
setAudioSegments([]);
|
||||
setSelectedAudioSegmentId("");
|
||||
setCurrentTime(0);
|
||||
setIsPlaying(false);
|
||||
setStatus("ready");
|
||||
@@ -2473,7 +2504,20 @@ export function App() {
|
||||
|
||||
async function commitAudio(blob, nextStatusText) {
|
||||
const decoded = await decodeWaveform(blob);
|
||||
replaceAudio(blob, decoded.duration, decoded.peaks, nextStatusText);
|
||||
const audioSegment = replaceAudio(blob, decoded.duration, decoded.peaks, nextStatusText);
|
||||
const generatedCaptions = createCaptionSegments(script);
|
||||
const generatedTimeline = getCaptionTimeline(generatedCaptions, audioSegment.duration);
|
||||
const boundCaptions = generatedCaptions.map((segment, index) => ({
|
||||
...segment,
|
||||
audioSegmentId: audioSegment.id,
|
||||
start: audioSegment.start + generatedTimeline[index].start,
|
||||
end: audioSegment.start + generatedTimeline[index].end,
|
||||
}));
|
||||
setCaptionSegments((segments) => [
|
||||
...segments.filter((segment) => segment.audioSegmentId),
|
||||
...boundCaptions,
|
||||
].sort((a, b) => (a.start || 0) - (b.start || 0)));
|
||||
setSelectedSegmentId(boundCaptions[0]?.id ?? "");
|
||||
setHistoryItems((items) => [
|
||||
{
|
||||
id: crypto.randomUUID(),
|
||||
@@ -2489,6 +2533,62 @@ export function App() {
|
||||
]);
|
||||
}
|
||||
|
||||
function updateAudioSegment(segmentId, patch) {
|
||||
setAudioSegments((segments) => segments.map((segment) => {
|
||||
if (segment.id !== segmentId) return segment;
|
||||
const next = { ...segment, ...patch };
|
||||
if (Number.isFinite(patch.start) && patch.start !== segment.start) {
|
||||
const delta = patch.start - segment.start;
|
||||
setCaptionSegments((captions) => captions.map((caption) =>
|
||||
caption.audioSegmentId === segmentId
|
||||
? { ...caption, start: caption.start + delta, end: caption.end + delta }
|
||||
: caption,
|
||||
));
|
||||
}
|
||||
setTimelineHorizon((value) => Math.max(value, Math.ceil((next.start + next.duration + 5) / 10) * 10));
|
||||
return next;
|
||||
}));
|
||||
}
|
||||
|
||||
async function toggleAudioSegmentReverse(segmentId) {
|
||||
const segment = audioSegments.find((item) => item.id === segmentId);
|
||||
if (!segment || segment.reversing) return;
|
||||
const audio = audioSegmentRefs.current.get(segmentId);
|
||||
audio?.pause();
|
||||
setAudioSegments((segments) => segments.map((item) => item.id === segmentId ? { ...item, reversing: true } : item));
|
||||
try {
|
||||
const originalBlob = segment.originalBlob || segment.blob;
|
||||
const originalPeaks = segment.originalPeaks || segment.peaks;
|
||||
const nextBlob = segment.reversed ? originalBlob : await reverseAudioBlob(originalBlob);
|
||||
const nextPeaks = segment.reversed ? originalPeaks : [...originalPeaks].reverse();
|
||||
const nextUrl = URL.createObjectURL(nextBlob);
|
||||
URL.revokeObjectURL(segment.url);
|
||||
setAudioSegments((segments) => segments.map((item) => item.id === segmentId ? {
|
||||
...item,
|
||||
blob: nextBlob,
|
||||
url: nextUrl,
|
||||
peaks: nextPeaks,
|
||||
reversed: !segment.reversed,
|
||||
reversing: false,
|
||||
originalBlob,
|
||||
originalPeaks,
|
||||
} : item));
|
||||
notify(segment.reversed ? t("audioReverseRestored") : t("audioReversed"));
|
||||
} catch (error) {
|
||||
setAudioSegments((segments) => segments.map((item) => item.id === segmentId ? { ...item, reversing: false } : item));
|
||||
notify(`${t("audioReverseFailed")}:${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
function deleteAudioSegment(segmentId) {
|
||||
const segment = audioSegments.find((item) => item.id === segmentId);
|
||||
if (segment) URL.revokeObjectURL(segment.url);
|
||||
setAudioSegments((segments) => segments.filter((item) => item.id !== segmentId));
|
||||
setCaptionSegments((segments) => segments.filter((item) => item.audioSegmentId !== segmentId));
|
||||
setSelectedAudioSegmentId((current) => current === segmentId ? "" : current);
|
||||
notify(t("audioClipDeleted"));
|
||||
}
|
||||
|
||||
async function commitRecordedVoice(blob, extension = "webm") {
|
||||
setRecordingState("processing");
|
||||
setStatus("generating");
|
||||
@@ -3375,7 +3475,7 @@ export function App() {
|
||||
}
|
||||
|
||||
function pauseTimelineMedia() {
|
||||
audioRef.current?.pause();
|
||||
audioSegmentRefs.current.forEach((audio) => audio.pause());
|
||||
sourceAudioRef.current?.pause();
|
||||
musicRef.current?.pause();
|
||||
previewVideoRef.current?.pause();
|
||||
@@ -3383,17 +3483,19 @@ export function App() {
|
||||
|
||||
function handlePlayToggle() {
|
||||
const previewVideo = previewVideoRef.current;
|
||||
const voiceAudio = trackVisibility.audio ? audioRef.current : null;
|
||||
const voiceAudios = trackVisibility.audio
|
||||
? audioSegments.map((segment) => ({ segment, audio: audioSegmentRefs.current.get(segment.id) })).filter((item) => item.audio)
|
||||
: [];
|
||||
const sourceAudio = trackVisibility.source ? sourceAudioRef.current : null;
|
||||
const musicAudio = trackVisibility.music ? musicRef.current : null;
|
||||
const currentTimelineTime = currentTimeRef.current;
|
||||
const syncVoiceAudioTime = () => {
|
||||
if (!voiceAudio || !audioUrl) {
|
||||
return false;
|
||||
}
|
||||
const syncVoiceAudio = ({ segment, audio }) => {
|
||||
const timelineTime = currentTimeRef.current;
|
||||
voiceAudio.currentTime = Math.max(0, Math.min(audioDuration || timelineTime, timelineTime));
|
||||
return timelineTime <= (audioDuration || timelineTime);
|
||||
const active = isTimelineTimeInsideTrack(timelineTime, segment.start, segment.duration);
|
||||
audio.currentTime = getTimelineTrackLocalTime(timelineTime, segment.start, segment.duration);
|
||||
audio.volume = getAudioSegmentPreviewVolume(segment, timelineTime);
|
||||
audio.playbackRate = 1;
|
||||
return active;
|
||||
};
|
||||
const syncSourceAudioTime = () => {
|
||||
if (!sourceAudio || !sourceAudioUrl) {
|
||||
@@ -3449,9 +3551,7 @@ export function App() {
|
||||
|
||||
const nextTime = currentTimeRef.current;
|
||||
if (nextTime !== currentTimelineTime) {
|
||||
if (voiceAudio && audioUrl) {
|
||||
voiceAudio.currentTime = 0;
|
||||
}
|
||||
voiceAudios.forEach(({ audio }) => { audio.currentTime = 0; });
|
||||
if (sourceAudio && sourceAudioUrl) {
|
||||
const localTime = getTimelineTrackLocalTime(nextTime, sourceAudioStart, sourceAudioDuration);
|
||||
sourceAudio.currentTime = localTime;
|
||||
@@ -3464,7 +3564,7 @@ export function App() {
|
||||
}
|
||||
}
|
||||
|
||||
playIfReady(voiceAudio, syncVoiceAudioTime());
|
||||
voiceAudios.forEach((item) => playIfReady(item.audio, syncVoiceAudio(item)));
|
||||
playIfReady(sourceAudio, syncSourceAudioTime());
|
||||
playIfReady(musicAudio, syncMusicTime());
|
||||
playIfReady(previewVideo, syncPreviewVideoTime());
|
||||
@@ -3472,12 +3572,13 @@ export function App() {
|
||||
}
|
||||
|
||||
function seekTo(nextTime) {
|
||||
const clamped = Math.max(0, Math.min(estimatedDuration, nextTime));
|
||||
const clamped = Math.max(0, Math.min(timelineDurationRef.current || MAX_TIMELINE_DURATION_SECONDS, nextTime));
|
||||
currentTimeRef.current = clamped;
|
||||
setCurrentTime(clamped);
|
||||
if (audioRef.current) {
|
||||
audioRef.current.currentTime = clamped;
|
||||
}
|
||||
audioSegments.forEach((segment) => {
|
||||
const audio = audioSegmentRefs.current.get(segment.id);
|
||||
if (audio) audio.currentTime = getTimelineTrackLocalTime(clamped, segment.start, segment.duration);
|
||||
});
|
||||
if (sourceAudioRef.current) {
|
||||
sourceAudioRef.current.currentTime = getTimelineTrackLocalTime(
|
||||
clamped,
|
||||
@@ -3521,6 +3622,56 @@ export function App() {
|
||||
window.addEventListener("pointerup", handlePointerUp, { once: true });
|
||||
}
|
||||
|
||||
function startAudioSegmentMove(event, segmentId = "") {
|
||||
if (event.button !== 0) return;
|
||||
const segment = audioSegments.find((item) => item.id === segmentId);
|
||||
if (!segment) return;
|
||||
if (trackLocks.audio) {
|
||||
notify(t("audioTrackLockedMove"));
|
||||
return;
|
||||
}
|
||||
const rect = trackScrollRef.current?.getBoundingClientRect();
|
||||
const duration = timelineDurationRef.current || 10;
|
||||
if (!rect) return;
|
||||
event.stopPropagation();
|
||||
setSelectedTrack("audio");
|
||||
setSelectedAudioSegmentId(segment.id);
|
||||
const startX = event.clientX;
|
||||
const startTime = segment.start || 0;
|
||||
const linkedCaptions = captionSegments.filter((caption) => caption.audioSegmentId === segment.id);
|
||||
let moved = false;
|
||||
let latestStart = startTime;
|
||||
const handlePointerMove = (moveEvent) => {
|
||||
if (!moved && Math.abs(moveEvent.clientX - startX) < 4) return;
|
||||
moved = true;
|
||||
moveEvent.preventDefault();
|
||||
const delta = ((moveEvent.clientX - startX) / Math.max(rect.width, 1)) * duration;
|
||||
latestStart = Math.max(0, Math.min(MAX_TIMELINE_DURATION_SECONDS - segment.duration, startTime + delta));
|
||||
setAudioSegments((segments) => segments.map((item) => item.id === segment.id ? { ...item, start: latestStart } : item));
|
||||
const captionDelta = latestStart - startTime;
|
||||
setCaptionSegments((captions) => captions.map((caption) => {
|
||||
const original = linkedCaptions.find((item) => item.id === caption.id);
|
||||
return original ? { ...caption, start: original.start + captionDelta, end: original.end + captionDelta } : caption;
|
||||
}));
|
||||
setTimelineHorizon((value) => Math.max(value, Math.ceil((latestStart + segment.duration + 5) / 10) * 10));
|
||||
};
|
||||
const cleanup = () => {
|
||||
window.removeEventListener("pointermove", handlePointerMove);
|
||||
window.removeEventListener("pointerup", handlePointerUp);
|
||||
window.removeEventListener("pointercancel", cleanup);
|
||||
};
|
||||
const handlePointerUp = () => {
|
||||
cleanup();
|
||||
if (moved) {
|
||||
seekTo(latestStart);
|
||||
notify(t("audioClipMoved"));
|
||||
}
|
||||
};
|
||||
window.addEventListener("pointermove", handlePointerMove, { passive: false });
|
||||
window.addEventListener("pointerup", handlePointerUp);
|
||||
window.addEventListener("pointercancel", cleanup);
|
||||
}
|
||||
|
||||
function startStickerSegmentMove(event, segmentId = "") {
|
||||
if (event.button !== 0) {
|
||||
return;
|
||||
@@ -3819,7 +3970,8 @@ export function App() {
|
||||
}
|
||||
: segment;
|
||||
}),
|
||||
audioBlob: trackVisibility.audio ? audioBlob : null,
|
||||
audioBlob: null,
|
||||
voiceAudioSegments: trackVisibility.audio ? audioSegments : [],
|
||||
voiceVolume: volume,
|
||||
sourceAudioBlob: trackVisibility.source ? sourceAudioBlob : null,
|
||||
sourceAudioVolume,
|
||||
@@ -3829,7 +3981,7 @@ export function App() {
|
||||
text: script,
|
||||
captionSegments,
|
||||
duration: Math.max(
|
||||
trackVisibility.audio && audioBlob ? audioDuration : 0,
|
||||
trackVisibility.audio ? voiceTrackDuration : 0,
|
||||
captionDuration,
|
||||
trackVisibility.source && sourceAudioBlob ? sourceAudioStart + sourceAudioDuration : 0,
|
||||
trackVisibility.music && musicBlob ? musicDuration : 0,
|
||||
@@ -3977,7 +4129,12 @@ export function App() {
|
||||
}
|
||||
|
||||
if (selectedTrack === "audio") {
|
||||
clearAudioTrack();
|
||||
const segmentId = selectedAudioSegmentId || selectedAudioSegment?.id;
|
||||
if (!segmentId) {
|
||||
notify("当前没有选中的配音片段");
|
||||
return;
|
||||
}
|
||||
deleteAudioSegment(segmentId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -4066,6 +4223,31 @@ export function App() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectedTrack === "audio") {
|
||||
if (!selectedAudioSegment) {
|
||||
notify(t("audioClipMissing"));
|
||||
return;
|
||||
}
|
||||
const id = crypto.randomUUID();
|
||||
const start = Math.min(MAX_TIMELINE_DURATION_SECONDS - selectedAudioSegment.duration, selectedAudioSegment.start + 0.2);
|
||||
const copy = {
|
||||
...selectedAudioSegment,
|
||||
id,
|
||||
url: URL.createObjectURL(selectedAudioSegment.blob),
|
||||
start,
|
||||
name: `${selectedAudioSegment.name || t("audioClip")} ${t("copySuffix")}`,
|
||||
};
|
||||
const delta = start - selectedAudioSegment.start;
|
||||
const copiedCaptions = captionSegments
|
||||
.filter((caption) => caption.audioSegmentId === selectedAudioSegment.id)
|
||||
.map((caption) => ({ ...caption, id: makeId("caption"), audioSegmentId: id, start: caption.start + delta, end: caption.end + delta }));
|
||||
setAudioSegments((segments) => [...segments, copy]);
|
||||
setCaptionSegments((segments) => [...segments, ...copiedCaptions].sort((a, b) => (a.start || 0) - (b.start || 0)));
|
||||
setSelectedAudioSegmentId(id);
|
||||
notify(t("audioClipDuplicated"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectedTrack === "music") {
|
||||
if (musicBlob) {
|
||||
downloadBlob(musicBlob, musicName || "background-music.wav");
|
||||
@@ -4840,6 +5022,8 @@ export function App() {
|
||||
notify={notify}
|
||||
audioUrl={audioUrl}
|
||||
audioRef={audioRef}
|
||||
audioSegments={audioSegments}
|
||||
audioSegmentRefs={audioSegmentRefs}
|
||||
sourceAudioRef={sourceAudioRef}
|
||||
musicRef={musicRef}
|
||||
sourceAudioUrl={sourceAudioUrl}
|
||||
@@ -4864,6 +5048,11 @@ export function App() {
|
||||
audioDuration={audioDuration}
|
||||
avatarJob={avatarJob}
|
||||
generateAvatarAcceptanceFrame={generateAvatarAcceptanceFrame}
|
||||
selectedTrack={selectedTrack}
|
||||
selectedAudioSegment={selectedAudioSegment}
|
||||
updateAudioSegment={updateAudioSegment}
|
||||
toggleAudioSegmentReverse={toggleAudioSegmentReverse}
|
||||
deleteAudioSegment={deleteAudioSegment}
|
||||
/>
|
||||
</section>
|
||||
|
||||
@@ -4939,6 +5128,10 @@ export function App() {
|
||||
peaks={peaks}
|
||||
audioClipPercent={audioClipPercent}
|
||||
audioDuration={audioDuration}
|
||||
audioSegments={audioSegments}
|
||||
selectedAudioSegmentId={selectedAudioSegmentId}
|
||||
setSelectedAudioSegmentId={setSelectedAudioSegmentId}
|
||||
startAudioSegmentMove={startAudioSegmentMove}
|
||||
musicBlob={musicBlob}
|
||||
musicPeaks={musicPeaks}
|
||||
musicClipPercent={musicClipPercent}
|
||||
|
||||
+118
-50
@@ -37,6 +37,35 @@ const TIMELINE_WHEEL_ZOOM_COMMIT_DELAY = 180;
|
||||
const TIMELINE_BUTTON_ZOOM_RATIO = 1.25;
|
||||
const VIDEO_FRAME_MIN_COUNT = 1;
|
||||
|
||||
function packAudioSegmentsIntoLanes(segments) {
|
||||
const lanes = [];
|
||||
[...segments].sort((a, b) => a.start - b.start || a.id.localeCompare(b.id)).forEach((segment) => {
|
||||
const laneIndex = lanes.findIndex((lane) => {
|
||||
const last = lane.at(-1);
|
||||
return !last || last.start + last.duration <= segment.start + 0.001;
|
||||
});
|
||||
if (laneIndex >= 0) lanes[laneIndex].push(segment);
|
||||
else lanes.push([segment]);
|
||||
});
|
||||
return lanes.length ? lanes : [[]];
|
||||
}
|
||||
|
||||
function packCaptionSegmentsIntoLanes(segments, timeline) {
|
||||
const lanes = [];
|
||||
segments
|
||||
.map((segment, index) => ({ segment, index, range: timeline[index] }))
|
||||
.sort((a, b) => (a.range?.start || 0) - (b.range?.start || 0))
|
||||
.forEach((item) => {
|
||||
const laneIndex = lanes.findIndex((lane) => {
|
||||
const last = lane.at(-1);
|
||||
return !last || (last.range?.end || 0) <= (item.range?.start || 0) + 0.001;
|
||||
});
|
||||
if (laneIndex >= 0) lanes[laneIndex].push(item);
|
||||
else lanes.push([item]);
|
||||
});
|
||||
return lanes.length ? lanes : [[]];
|
||||
}
|
||||
|
||||
function getSampledVideoFrames(frames, count) {
|
||||
if (!Array.isArray(frames) || !frames.length) {
|
||||
return [];
|
||||
@@ -149,6 +178,10 @@ export function Timeline({
|
||||
peaks,
|
||||
audioClipPercent,
|
||||
audioDuration,
|
||||
audioSegments,
|
||||
selectedAudioSegmentId,
|
||||
setSelectedAudioSegmentId,
|
||||
startAudioSegmentMove,
|
||||
musicBlob,
|
||||
musicPeaks,
|
||||
musicClipPercent,
|
||||
@@ -162,18 +195,20 @@ export function Timeline({
|
||||
activeTimelineClipDrag?.track === "caption"
|
||||
? displayedCaptionSegments.find((segment) => segment.id === activeTimelineClipDrag.segmentId)
|
||||
: null;
|
||||
const timelineTrackRows = showStickerTrack
|
||||
? "28px 46px 46px 46px 58px 58px 58px"
|
||||
: "28px 46px 46px 58px 58px 58px";
|
||||
const timelineLabelRows = showStickerTrack
|
||||
? "46px 46px 46px 58px 58px 58px"
|
||||
: "46px 46px 58px 58px 58px";
|
||||
const audioLanes = useMemo(() => packAudioSegmentsIntoLanes(audioSegments), [audioSegments]);
|
||||
const captionLanes = useMemo(
|
||||
() => packCaptionSegmentsIntoLanes(displayedCaptionSegments, displayedCaptionTimeline),
|
||||
[displayedCaptionSegments, displayedCaptionTimeline],
|
||||
);
|
||||
const contentRows = ["46px", ...(showStickerTrack ? ["46px"] : []), ...captionLanes.map(() => "46px"), "58px", ...audioLanes.map(() => "58px"), "58px"];
|
||||
const timelineTrackRows = ["28px", ...contentRows].join(" ");
|
||||
const timelineLabelRows = contentRows.join(" ");
|
||||
const timelineTrackLabels = [
|
||||
["image", t("imageTrack")],
|
||||
...(showStickerTrack ? [["sticker", t("stickerTrack")]] : []),
|
||||
["caption", t("caption")],
|
||||
...captionLanes.map((_, index) => ["caption", `${t("caption")} ${index + 1}`, `caption-${index}`]),
|
||||
["source", t("sourceTrack")],
|
||||
["audio", t("voiceTrack")],
|
||||
...audioLanes.map((_, index) => ["audio", `${t("voiceTrack")} ${index + 1}`, `audio-${index}`]),
|
||||
["music", t("musicTrack")],
|
||||
];
|
||||
const [rulerViewport, setRulerViewport] = useState({
|
||||
@@ -326,7 +361,18 @@ export function Timeline({
|
||||
window.requestAnimationFrame(syncScrollAnchor);
|
||||
};
|
||||
const handleTimelineWheel = (event) => {
|
||||
if (event.shiftKey || Math.abs(event.deltaX) > Math.abs(event.deltaY)) {
|
||||
if (!event.ctrlKey && !event.metaKey) {
|
||||
if (!event.shiftKey && Math.abs(event.deltaY) >= Math.abs(event.deltaX)) {
|
||||
const board = event.currentTarget?.closest?.(".timeline")?.querySelector?.(".timeline-board");
|
||||
if (board && board.scrollHeight > board.clientHeight) {
|
||||
event.preventDefault();
|
||||
board.scrollTop += event.deltaY;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (Math.abs(event.deltaX) > Math.abs(event.deltaY)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -537,8 +583,8 @@ export function Timeline({
|
||||
|
||||
<div className="timeline-board">
|
||||
<div className="track-labels" style={{ gridTemplateRows: timelineLabelRows }}>
|
||||
{timelineTrackLabels.map(([track, label]) => (
|
||||
<div className={selectedTrack === track ? "is-selected" : ""} key={track}>
|
||||
{timelineTrackLabels.map(([track, label, rowId = track]) => (
|
||||
<div className={selectedTrack === track ? "is-selected" : ""} key={rowId}>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`${label} ${t("visible")}`}
|
||||
@@ -752,20 +798,21 @@ export function Timeline({
|
||||
{renderAssetDropSlot("image")}
|
||||
</div>
|
||||
{renderStickerTrack()}
|
||||
<div
|
||||
className={`caption-track ${selectedTrack === "caption" ? "is-selected" : ""} ${
|
||||
activeTimelineClipDrag?.track === "caption" ? "is-reordering" : ""
|
||||
}`}
|
||||
onClick={() => {
|
||||
setSelectedTrack("caption");
|
||||
setActiveTool("caption");
|
||||
}}
|
||||
data-timeline-reorder-track="caption"
|
||||
>
|
||||
{trackVisibility.caption
|
||||
? displayedCaptionSegments.map((segment, index) => {
|
||||
const segmentRange = displayedCaptionTimeline[index];
|
||||
const segmentDuration = displayedCaptionTimeline[index]?.duration ?? 0;
|
||||
{captionLanes.map((lane, laneIndex) => (
|
||||
<div
|
||||
className={`caption-track ${selectedTrack === "caption" ? "is-selected" : ""} ${
|
||||
activeTimelineClipDrag?.track === "caption" ? "is-reordering" : ""
|
||||
}`}
|
||||
key={`caption-lane-${laneIndex}`}
|
||||
onClick={() => {
|
||||
setSelectedTrack("caption");
|
||||
setActiveTool("caption");
|
||||
}}
|
||||
data-timeline-reorder-track="caption"
|
||||
>
|
||||
{trackVisibility.caption
|
||||
? lane.map(({ segment, index, range: segmentRange }) => {
|
||||
const segmentDuration = segmentRange?.duration ?? 0;
|
||||
const segmentLeft =
|
||||
segmentRange && timelineDuration > 0
|
||||
? Math.max(0, Math.min(100, (segmentRange.start / timelineDuration) * 100))
|
||||
@@ -815,9 +862,10 @@ export function Timeline({
|
||||
{segment.text}
|
||||
</button>
|
||||
);
|
||||
})
|
||||
: null}
|
||||
</div>
|
||||
})
|
||||
: null}
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
className={`audio-track source-track ${selectedTrack === "source" ? "is-selected" : ""} ${
|
||||
assetDropTargetTrack === "source" ? "is-drop-target" : ""
|
||||
@@ -846,28 +894,48 @@ export function Timeline({
|
||||
</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>
|
||||
{audioLanes.map((lane, laneIndex) => (
|
||||
<button
|
||||
className={`audio-track ${selectedTrack === "audio" ? "is-selected" : ""} ${
|
||||
laneIndex === 0 && assetDropTargetTrack === "audio" ? "is-drop-target" : ""
|
||||
} ${laneIndex === 0 && assetDropPulseTrack === "audio" ? "is-drop-landing" : ""}`}
|
||||
type="button"
|
||||
key={`audio-lane-${laneIndex}`}
|
||||
onClick={() => setSelectedTrack("audio")}
|
||||
onDragOver={(event) => laneIndex === 0 && handleTrackAssetDragOver(event, "audio")}
|
||||
onDragLeave={(event) => laneIndex === 0 && handleTrackAssetDragLeave(event, "audio")}
|
||||
onDrop={(event) => laneIndex === 0 && handleTrackAssetDrop(event, "audio")}
|
||||
data-asset-drop-track={laneIndex === 0 ? "audio" : undefined}
|
||||
>
|
||||
{laneIndex === 0 && assetDropTargetTrack === "audio" ? (
|
||||
<div className="track-drop-hint">{t("dropVoiceHere")}</div>
|
||||
) : null}
|
||||
{laneIndex === 0 ? renderAssetDropSlot("audio") : null}
|
||||
{trackVisibility.audio
|
||||
? lane.map((segment) => {
|
||||
const left = timelineDuration > 0 ? (segment.start / timelineDuration) * 100 : 0;
|
||||
const width = timelineDuration > 0 ? (segment.duration / timelineDuration) * 100 : 0;
|
||||
return (
|
||||
<div
|
||||
className={`audio-clip ${selectedAudioSegmentId === segment.id ? "is-selected" : ""}`}
|
||||
key={segment.id}
|
||||
style={{ left: `${left}%`, width: `${width}%` }}
|
||||
onPointerDown={(event) => startAudioSegmentMove(event, segment.id)}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
setSelectedTrack("audio");
|
||||
setSelectedAudioSegmentId(segment.id);
|
||||
seekTo(segment.start);
|
||||
}}
|
||||
>
|
||||
<WaveformStrip peaks={segment.peaks} active />
|
||||
<span className="audio-clip-duration">{formatTime(segment.duration)}</span>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
: null}
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
className={`audio-track music-track ${selectedTrack === "music" ? "is-selected" : ""} ${
|
||||
assetDropTargetTrack === "music" ? "is-drop-target" : ""
|
||||
|
||||
@@ -139,6 +139,40 @@ function CaptionContextPanel({
|
||||
);
|
||||
}
|
||||
|
||||
function AudioClipContextPanel({ t, segment, updateAudioSegment, toggleAudioSegmentReverse, deleteAudioSegment, downloadBlob }) {
|
||||
return (
|
||||
<div className="audio-clip-context-panel">
|
||||
<div className="avatar-context-hero">
|
||||
<span><Waveform size={22} weight="duotone" /></span>
|
||||
<div><small>{t("voiceTrack")}</small><strong>{segment.name || t("audioClip")}</strong><em>{formatTime(segment.duration)}</em></div>
|
||||
</div>
|
||||
<label className="audio-property-row">
|
||||
<span>{t("audioClipStart")}</span>
|
||||
<input type="number" min="0" step="0.1" value={Number(segment.start.toFixed(1))} onChange={(event) => updateAudioSegment(segment.id, { start: Math.max(0, Number(event.target.value) || 0) })} />
|
||||
</label>
|
||||
<label className="audio-property-slider">
|
||||
<span><b>{t("volume")}</b><em>{Math.round((segment.volume ?? 1) * 100)}%</em></span>
|
||||
<input type="range" min="0" max="1" step="0.01" value={segment.volume ?? 1} onChange={(event) => updateAudioSegment(segment.id, { volume: Number(event.target.value) })} />
|
||||
</label>
|
||||
<label className="audio-property-slider">
|
||||
<span><b>{t("fadeIn")}</b><em>{(segment.fadeIn ?? 0).toFixed(1)}s</em></span>
|
||||
<input type="range" min="0" max={Math.min(3, segment.duration / 2)} step="0.1" value={segment.fadeIn ?? 0} onChange={(event) => updateAudioSegment(segment.id, { fadeIn: Number(event.target.value) })} />
|
||||
</label>
|
||||
<label className="audio-property-slider">
|
||||
<span><b>{t("fadeOut")}</b><em>{(segment.fadeOut ?? 0).toFixed(1)}s</em></span>
|
||||
<input type="range" min="0" max={Math.min(3, segment.duration / 2)} step="0.1" value={segment.fadeOut ?? 0} onChange={(event) => updateAudioSegment(segment.id, { fadeOut: Number(event.target.value) })} />
|
||||
</label>
|
||||
<div className="audio-context-actions">
|
||||
<button className={`panel-secondary ${segment.reversed ? "is-active" : ""}`} type="button" disabled={segment.reversing} onClick={() => toggleAudioSegmentReverse(segment.id)}>
|
||||
{segment.reversing ? t("audioReversing") : segment.reversed ? t("audioReverseRestore") : t("audioReverse")}
|
||||
</button>
|
||||
<button className="panel-secondary" type="button" onClick={() => downloadBlob(segment.blob, `${segment.name || "voiceover"}.wav`)}>{t("downloadAudioClip")}</button>
|
||||
<button className="panel-secondary is-danger" type="button" onClick={() => deleteAudioSegment(segment.id)}><Trash size={15} />{t("deleteAudioClip")}</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AvatarContextPanel({ t, hasVisual, visualType, audioBlob, audioDuration, captionSegments, selectedVoice, avatarJob, generateAvatarAcceptanceFrame }) {
|
||||
const hasPortrait = hasVisual && visualType === "image";
|
||||
const [probeState, setProbeState] = useState("idle");
|
||||
@@ -249,6 +283,8 @@ export function VoicePanel({
|
||||
notify,
|
||||
audioUrl,
|
||||
audioRef,
|
||||
audioSegments,
|
||||
audioSegmentRefs,
|
||||
sourceAudioRef,
|
||||
musicRef,
|
||||
sourceAudioUrl,
|
||||
@@ -273,22 +309,30 @@ export function VoicePanel({
|
||||
audioDuration,
|
||||
avatarJob,
|
||||
generateAvatarAcceptanceFrame,
|
||||
selectedTrack,
|
||||
selectedAudioSegment,
|
||||
updateAudioSegment,
|
||||
toggleAudioSegmentReverse,
|
||||
deleteAudioSegment,
|
||||
}) {
|
||||
const isCaptionContext = activeTool === "caption";
|
||||
const isAvatarContext = activeTool === "smart" && avatarPanelOpen;
|
||||
const title = isAvatarContext ? t("avatarTitle") : isCaptionContext ? t("caption") : t("aiVoice");
|
||||
const isAudioClipContext = selectedTrack === "audio" && Boolean(selectedAudioSegment);
|
||||
const title = isAvatarContext ? t("avatarTitle") : isCaptionContext ? t("caption") : isAudioClipContext ? t("audioClipProperties") : t("aiVoice");
|
||||
const panelStatusText = isCaptionContext
|
||||
? captionSegments.length
|
||||
? `${captionSegments.length} ${t("captionSegmentsUnit", "条字幕")}`
|
||||
: t("noCaptionSegments")
|
||||
: isAvatarContext
|
||||
? t("avatarPortingStatus")
|
||||
: isAudioClipContext
|
||||
? `${formatTime(selectedAudioSegment.duration)} · ${selectedAudioSegment.start.toFixed(1)}s`
|
||||
: statusText === "模型待命"
|
||||
? t("modelReady")
|
||||
: statusText;
|
||||
|
||||
return (
|
||||
<aside className={`voice-panel ${isCaptionContext ? "is-caption-context" : ""} ${isAvatarContext ? "is-avatar-context" : ""}`}>
|
||||
<aside className={`voice-panel ${isCaptionContext ? "is-caption-context" : ""} ${isAvatarContext ? "is-avatar-context" : ""} ${isAudioClipContext ? "is-audio-clip-context" : ""}`}>
|
||||
<div className="panel-title-row">
|
||||
<h1>{title}</h1>
|
||||
<span className={`status-pill ${isCaptionContext ? "done" : status}`}>
|
||||
@@ -296,7 +340,7 @@ export function VoicePanel({
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{!isCaptionContext && !isAvatarContext ? (
|
||||
{!isCaptionContext && !isAvatarContext && !isAudioClipContext ? (
|
||||
<div className="tabs compact">
|
||||
{[
|
||||
["synthesis", t("voiceSynthesis")],
|
||||
@@ -338,7 +382,9 @@ export function VoicePanel({
|
||||
|
||||
{isAvatarContext ? <AvatarContextPanel t={t} hasVisual={hasVisual} visualType={visualType} audioBlob={audioBlob} audioDuration={audioDuration} captionSegments={captionSegments} selectedVoice={selectedVoice} avatarJob={avatarJob} generateAvatarAcceptanceFrame={generateAvatarAcceptanceFrame} /> : null}
|
||||
|
||||
{!isCaptionContext && !isAvatarContext && voiceTab === "synthesis" ? (
|
||||
{isAudioClipContext ? <AudioClipContextPanel t={t} segment={selectedAudioSegment} updateAudioSegment={updateAudioSegment} toggleAudioSegmentReverse={toggleAudioSegmentReverse} deleteAudioSegment={deleteAudioSegment} downloadBlob={downloadBlob} /> : null}
|
||||
|
||||
{!isCaptionContext && !isAvatarContext && !isAudioClipContext && voiceTab === "synthesis" ? (
|
||||
<VoiceSynthesisPanel
|
||||
script={script}
|
||||
updateScript={updateScript}
|
||||
@@ -365,7 +411,7 @@ export function VoicePanel({
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{!isCaptionContext && !isAvatarContext && voiceTab === "mine" ? (
|
||||
{!isCaptionContext && !isAvatarContext && !isAudioClipContext && voiceTab === "mine" ? (
|
||||
<MyVoicesPanel
|
||||
favoriteVoiceIds={favoriteVoiceIds}
|
||||
setFavoriteVoiceIds={setFavoriteVoiceIds}
|
||||
@@ -383,7 +429,7 @@ export function VoicePanel({
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{!isCaptionContext && !isAvatarContext && voiceTab === "history" ? (
|
||||
{!isCaptionContext && !isAvatarContext && !isAudioClipContext && voiceTab === "history" ? (
|
||||
<HistoryPanel
|
||||
historyItems={historyItems}
|
||||
useHistoryItem={useHistoryItem}
|
||||
@@ -394,12 +440,17 @@ export function VoicePanel({
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{audioUrl ? (
|
||||
{audioSegments.map((segment) => (
|
||||
<audio
|
||||
ref={audioRef}
|
||||
src={audioUrl}
|
||||
key={segment.id}
|
||||
ref={(node) => {
|
||||
if (node) audioSegmentRefs.current.set(segment.id, node);
|
||||
else audioSegmentRefs.current.delete(segment.id);
|
||||
if (segment.id === audioSegments.at(-1)?.id) audioRef.current = node;
|
||||
}}
|
||||
src={segment.url}
|
||||
/>
|
||||
) : null}
|
||||
))}
|
||||
{sourceAudioUrl ? (
|
||||
<audio
|
||||
ref={sourceAudioRef}
|
||||
|
||||
@@ -15,7 +15,8 @@ export { MODEL_ID, AUTOMATIC_CAPTION_MODEL_ID, AUTOMATIC_CAPTION_MODEL_LABEL } f
|
||||
export const SAMPLE_IMAGE = "/assets/sample-portrait.png";
|
||||
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 DEFAULT_TIMELINE_DURATION_SECONDS = 30 * 60;
|
||||
export const MAX_TIMELINE_DURATION_SECONDS = 24 * 60 * 60;
|
||||
export const IMAGE_SEGMENT_SECONDS = 2;
|
||||
export const MIN_VISUAL_SEGMENT_SECONDS = 0.5;
|
||||
export const MAX_IMAGE_THUMBNAILS = 80;
|
||||
|
||||
+38
@@ -235,6 +235,25 @@ export const UI_COPY = {
|
||||
ttsErrorUnsupportedPiperSymbols: "当前中文语音模型不支持这段文案里的部分字符,请清理英文/特殊符号,或切换 English 声音。",
|
||||
ttsErrorStorageQuota: "浏览器模型缓存空间不足,请在设置里清理模型缓存后重试。",
|
||||
ttsErrorGenerationFailed: "生成失败,请重试",
|
||||
audioClipProperties: "音频片段属性",
|
||||
audioClip: "配音片段",
|
||||
audioClipStart: "时间轴位置(秒)",
|
||||
fadeIn: "淡入",
|
||||
fadeOut: "淡出",
|
||||
audioReverse: "反转音频",
|
||||
audioReverseRestore: "恢复正向",
|
||||
audioReversing: "正在反转…",
|
||||
audioReversed: "音频已反转,试听、波形与导出已同步",
|
||||
audioReverseRestored: "音频已恢复正向播放",
|
||||
audioReverseFailed: "音频反转失败",
|
||||
downloadAudioClip: "下载片段",
|
||||
deleteAudioClip: "删除片段",
|
||||
audioClipDeleted: "配音片段已删除",
|
||||
audioClipMoved: "配音片段位置已调整",
|
||||
audioTrackLockedMove: "配音轨已锁定,无法移动片段",
|
||||
audioClipMissing: "当前没有选中的配音片段",
|
||||
audioClipDuplicated: "配音片段已复制到新轨道",
|
||||
copySuffix: "副本",
|
||||
top: "顶部",
|
||||
middle: "居中",
|
||||
bottom: "底部",
|
||||
@@ -534,6 +553,25 @@ export const UI_COPY = {
|
||||
ttsErrorUnsupportedPiperSymbols: "The Chinese voice model does not support some characters in this script. Remove English or special symbols, or switch to an English voice.",
|
||||
ttsErrorStorageQuota: "Browser model storage is full. Clear the model cache in Settings and try again.",
|
||||
ttsErrorGenerationFailed: "Generation failed. Try again.",
|
||||
audioClipProperties: "Audio clip properties",
|
||||
audioClip: "Voiceover clip",
|
||||
audioClipStart: "Timeline position (seconds)",
|
||||
fadeIn: "Fade in",
|
||||
fadeOut: "Fade out",
|
||||
audioReverse: "Reverse audio",
|
||||
audioReverseRestore: "Restore forward",
|
||||
audioReversing: "Reversing…",
|
||||
audioReversed: "Audio reversed; preview, waveform, and export are synchronized",
|
||||
audioReverseRestored: "Audio restored to forward playback",
|
||||
audioReverseFailed: "Audio reverse failed",
|
||||
downloadAudioClip: "Download clip",
|
||||
deleteAudioClip: "Delete clip",
|
||||
audioClipDeleted: "Voiceover clip deleted.",
|
||||
audioClipMoved: "Voiceover clip position updated.",
|
||||
audioTrackLockedMove: "The voiceover track is locked.",
|
||||
audioClipMissing: "No voiceover clip is selected.",
|
||||
audioClipDuplicated: "Voiceover clip duplicated to a new lane.",
|
||||
copySuffix: "copy",
|
||||
top: "Top",
|
||||
middle: "Middle",
|
||||
bottom: "Bottom",
|
||||
|
||||
+75
-2
@@ -166,6 +166,59 @@ export async function decodeWaveform(blob, barCount = 118) {
|
||||
}
|
||||
}
|
||||
|
||||
function encodeAudioBufferAsWav(buffer) {
|
||||
const channels = Math.max(1, buffer.numberOfChannels);
|
||||
const frames = buffer.length;
|
||||
const bytesPerSample = 2;
|
||||
const blockAlign = channels * bytesPerSample;
|
||||
const output = new ArrayBuffer(44 + frames * blockAlign);
|
||||
const view = new DataView(output);
|
||||
const writeText = (offset, text) => {
|
||||
for (let index = 0; index < text.length; index += 1) view.setUint8(offset + index, text.charCodeAt(index));
|
||||
};
|
||||
writeText(0, "RIFF");
|
||||
view.setUint32(4, output.byteLength - 8, true);
|
||||
writeText(8, "WAVE");
|
||||
writeText(12, "fmt ");
|
||||
view.setUint32(16, 16, true);
|
||||
view.setUint16(20, 1, true);
|
||||
view.setUint16(22, channels, true);
|
||||
view.setUint32(24, buffer.sampleRate, true);
|
||||
view.setUint32(28, buffer.sampleRate * blockAlign, true);
|
||||
view.setUint16(32, blockAlign, true);
|
||||
view.setUint16(34, 16, true);
|
||||
writeText(36, "data");
|
||||
view.setUint32(40, frames * blockAlign, true);
|
||||
const channelData = Array.from({ length: channels }, (_, channel) => buffer.getChannelData(channel));
|
||||
let offset = 44;
|
||||
for (let frame = 0; frame < frames; frame += 1) {
|
||||
for (let channel = 0; channel < channels; channel += 1) {
|
||||
const sample = Math.max(-1, Math.min(1, channelData[channel][frame]));
|
||||
view.setInt16(offset, sample < 0 ? sample * 0x8000 : sample * 0x7fff, true);
|
||||
offset += bytesPerSample;
|
||||
}
|
||||
}
|
||||
return new Blob([output], { type: "audio/wav" });
|
||||
}
|
||||
|
||||
export async function reverseAudioBlob(blob) {
|
||||
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
|
||||
if (!AudioContextClass) throw new Error("当前浏览器不支持 AudioContext,无法反转音频。");
|
||||
const context = new AudioContextClass();
|
||||
try {
|
||||
const decoded = await context.decodeAudioData((await blob.arrayBuffer()).slice(0));
|
||||
const reversed = context.createBuffer(decoded.numberOfChannels, decoded.length, decoded.sampleRate);
|
||||
for (let channel = 0; channel < decoded.numberOfChannels; channel += 1) {
|
||||
const source = decoded.getChannelData(channel);
|
||||
const target = reversed.getChannelData(channel);
|
||||
for (let index = 0; index < source.length; index += 1) target[index] = source[source.length - 1 - index];
|
||||
}
|
||||
return encodeAudioBufferAsWav(reversed);
|
||||
} finally {
|
||||
await context.close().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
export function downloadBlob(blob, filename) {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const anchor = document.createElement("a");
|
||||
@@ -548,6 +601,7 @@ export async function exportBrowserVideo({
|
||||
visualType,
|
||||
visualSegments = [],
|
||||
audioBlob,
|
||||
voiceAudioSegments = [],
|
||||
voiceVolume = 1,
|
||||
sourceAudioBlob,
|
||||
sourceAudioVolume = 1,
|
||||
@@ -652,7 +706,17 @@ export async function exportBrowserVideo({
|
||||
const sources = [];
|
||||
let destination = null;
|
||||
const audioInputs = [
|
||||
audioBlob ? { blob: audioBlob, volume: voiceVolume, role: "voice", start: 0 } : null,
|
||||
...voiceAudioSegments.map((segment) => ({
|
||||
blob: segment.blob,
|
||||
volume: segment.volume ?? 1,
|
||||
role: "voice",
|
||||
start: Math.max(0, segment.start || 0),
|
||||
fadeIn: Math.max(0, segment.fadeIn || 0),
|
||||
fadeOut: Math.max(0, segment.fadeOut || 0),
|
||||
})),
|
||||
audioBlob && !voiceAudioSegments.length
|
||||
? { blob: audioBlob, volume: voiceVolume, role: "voice", start: 0, fadeIn: 0, fadeOut: 0 }
|
||||
: null,
|
||||
sourceAudioBlob
|
||||
? { blob: sourceAudioBlob, volume: sourceAudioVolume, role: "source", start: Math.max(0, sourceAudioStart || 0) }
|
||||
: null,
|
||||
@@ -675,13 +739,22 @@ export async function exportBrowserVideo({
|
||||
}),
|
||||
);
|
||||
|
||||
decodedDuration = decodedInputs.find((input) => input.role === "voice")?.decoded.duration ?? 0;
|
||||
decodedDuration = Math.max(0, ...decodedInputs.filter((input) => input.role === "voice").map((input) => input.start + input.decoded.duration));
|
||||
|
||||
decodedInputs.forEach((input) => {
|
||||
const source = audioContext.createBufferSource();
|
||||
const gain = audioContext.createGain();
|
||||
source.buffer = input.decoded;
|
||||
gain.gain.value = input.volume;
|
||||
if (input.fadeIn > 0) {
|
||||
gain.gain.setValueAtTime(0, audioContext.currentTime + input.start);
|
||||
gain.gain.linearRampToValueAtTime(input.volume, audioContext.currentTime + input.start + input.fadeIn);
|
||||
}
|
||||
if (input.fadeOut > 0) {
|
||||
const fadeStart = audioContext.currentTime + input.start + Math.max(0, input.decoded.duration - input.fadeOut);
|
||||
gain.gain.setValueAtTime(input.volume, fadeStart);
|
||||
gain.gain.linearRampToValueAtTime(0, audioContext.currentTime + input.start + input.decoded.duration);
|
||||
}
|
||||
source.connect(gain);
|
||||
gain.connect(destination);
|
||||
sources.push({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { MAX_TIMELINE_DURATION_SECONDS } from "../config/editor.js";
|
||||
import { DEFAULT_TIMELINE_DURATION_SECONDS } from "../config/editor.js";
|
||||
|
||||
export const TIMELINE_MIN_ZOOM = 0.25;
|
||||
export const TIMELINE_MAX_ZOOM = 16;
|
||||
@@ -18,7 +18,7 @@ export function getTimelineVisibleDuration(zoom) {
|
||||
|
||||
if (clampedZoom <= 1) {
|
||||
const progress = (clampedZoom - TIMELINE_MIN_ZOOM) / (1 - TIMELINE_MIN_ZOOM);
|
||||
const maxLog = Math.log(MAX_TIMELINE_DURATION_SECONDS);
|
||||
const maxLog = Math.log(DEFAULT_TIMELINE_DURATION_SECONDS);
|
||||
const defaultLog = Math.log(TIMELINE_DEFAULT_VISIBLE_SECONDS);
|
||||
return Math.exp(maxLog + (defaultLog - maxLog) * progress);
|
||||
}
|
||||
|
||||
@@ -1489,6 +1489,14 @@ button:disabled {
|
||||
.avatar-open-button { display: flex; align-items: center; justify-content: center; gap: 6px; min-height: 36px; width: 100%; font-size: 11px; }
|
||||
|
||||
.avatar-context-panel { display: grid; gap: 14px; }
|
||||
.audio-clip-context-panel { display: grid; gap: 14px; }
|
||||
.audio-property-row { display: grid; grid-template-columns: 1fr 92px; align-items: center; gap: 10px; color: #9aa8b8; font-size: 11px; }
|
||||
.audio-property-row input { min-width: 0; height: 32px; border: 1px solid rgba(255,255,255,.1); border-radius: 7px; padding: 0 8px; color: #eaf6f7; background: rgba(255,255,255,.04); }
|
||||
.audio-property-slider { display: grid; gap: 8px; }
|
||||
.audio-property-slider > span { display: flex; justify-content: space-between; gap: 10px; color: #94a2b0; font-size: 11px; }
|
||||
.audio-property-slider b { color: #dce7eb; font-weight: 650; }.audio-property-slider em { color: #69e4d9; font-style: normal; }
|
||||
.audio-property-slider input { width: 100%; accent-color: #35ead9; }
|
||||
.audio-context-actions { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }.audio-context-actions button { display: flex; align-items: center; justify-content: center; gap: 6px; min-height: 36px; }.audio-context-actions .is-danger { color: #ff969b; }
|
||||
.avatar-context-hero { display: grid; grid-template-columns: 42px minmax(0, 1fr); gap: 10px; align-items: start; padding: 13px; border: 1px solid rgba(109, 137, 255, .22); border-radius: 10px; background: linear-gradient(135deg, rgba(85, 112, 235, .15), rgba(53, 234, 217, .05)); }
|
||||
.avatar-context-hero > span { display: grid; place-items: center; width: 42px; height: 42px; border-radius: 10px; color: #b4c7ff; background: rgba(108, 137, 255, .18); }
|
||||
.avatar-context-hero > div { display: grid; gap: 4px; }
|
||||
@@ -3095,8 +3103,16 @@ button:disabled {
|
||||
display: grid;
|
||||
grid-template-columns: 128px 1fr;
|
||||
min-height: 0;
|
||||
max-height: min(430px, 48vh);
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
scrollbar-color: rgba(143, 158, 172, 0.42) transparent;
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
|
||||
.timeline-board::-webkit-scrollbar { width: 7px; }
|
||||
.timeline-board::-webkit-scrollbar-thumb { border-radius: 999px; background: rgba(143, 158, 172, 0.42); }
|
||||
|
||||
.track-labels {
|
||||
display: grid;
|
||||
grid-template-rows: 46px 46px 58px 58px 58px;
|
||||
@@ -3745,6 +3761,21 @@ button:disabled {
|
||||
height: 44px;
|
||||
}
|
||||
|
||||
.audio-track:not(.source-track):not(.music-track) .audio-clip {
|
||||
position: absolute;
|
||||
top: 7px;
|
||||
cursor: grab;
|
||||
}
|
||||
|
||||
.audio-track:not(.source-track):not(.music-track) .audio-clip:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
.audio-clip.is-selected .waveform-strip {
|
||||
border-color: rgba(105, 170, 255, 0.95);
|
||||
box-shadow: inset 0 0 0 1px rgba(105, 170, 255, 0.45);
|
||||
}
|
||||
|
||||
.audio-clip.is-source .waveform-strip {
|
||||
border-color: rgba(250, 194, 93, 0.52);
|
||||
background: rgba(125, 88, 22, 0.26);
|
||||
|
||||
Reference in new issue
Block a user