Skip to content

🎬 火宝短剧 - 基于AI的一站式短剧生成平台 《一句话生成完整短剧,从剧本到成片全自动化》 Huobao Drama - An AI-Powered End-to-End Short Drama Generator "One Sentence to Complete Drama: Fully Automated from Script to Final Video"

TypeScript

fix: 修复视频下载报错 修复本地视频文件合成后删除问题 修复视频合并文件与所选文件不一致问题

jiangzj306b039d8cf9
diff --git a/application/services/video_merge_service.go b/application/services/video_merge_service.go
index 8671e21..4fcdea6 100644
--- a/application/services/video_merge_service.go
+++ b/application/services/video_merge_service.go
@@ -160,8 +160,13 @@ func (s *VideoMergeService) mergeVideoClips(client video.VideoClient, scenes []m
// 准备FFmpeg合成选项
clips := make([]ffmpeg.VideoClip, len(scenes))
for i, scene := range scenes {
+ // 使用 scene.VideoURL,它已经在前面的代码中被正确处理
+ // 如果是本地文件,已经包含了完整路径(storagePath + LocalPath)
+ // 如果是 HTTP URL,则直接使用
+ videoPath := scene.VideoURL
+
clips[i] = ffmpeg.VideoClip{
- URL: scene.VideoURL,
+ URL: videoPath,
Duration: scene.Duration,
StartTime: scene.StartTime,
EndTime: scene.EndTime,
@@ -171,6 +176,7 @@ func (s *VideoMergeService) mergeVideoClips(client video.VideoClient, scenes []m
s.log.Infow("Clip added to merge queue",
"order", scene.Order,
"index", i,
+ "video_path", videoPath,
"duration", scene.Duration,
"start_time", scene.StartTime,
"end_time", scene.EndTime)
@@ -197,12 +203,11 @@ func (s *VideoMergeService) mergeVideoClips(client video.VideoClient, scenes []m
s.log.Infow("Video merged successfully", "path", mergedPath)
- // 生成访问URL(相对路径)
+ // 生成相对路径(不包含协议、IP、端口)
relPath := filepath.Join("videos", "merged", fileName)
- videoURL := fmt.Sprintf("%s/%s", s.baseURL, relPath)
result := &video.VideoResult{
- VideoURL: videoURL, // 返回可访问的URL
+ VideoURL: relPath, // 只保存相对路径
Duration: int(totalDuration),
Completed: true,
Status: "completed",
@@ -371,7 +376,7 @@ func (s *VideoMergeService) DeleteMerge(mergeID uint) error {
// TimelineClip 时间线片段数据
type TimelineClip struct {
- AssetID string `json:"asset_id"` // 素材库视频ID(优先使用)
+ AssetID interface{} `json:"asset_id"` // 素材库视频ID(优先使用,可以是数字或字符串)
StoryboardID string `json:"storyboard_id"` // 分镜ID(fallback)
Order int `json:"order"`
StartTime float64 `json:"start_time"`
@@ -380,6 +385,23 @@ type TimelineClip struct {
Transition map[string]interface{} `json:"transition"`
}
+// getAssetIDString 将 AssetID 转换为字符串
+func getAssetIDString(assetID interface{}) string {
+ if assetID == nil {
+ return ""
+ }
+ switch v := assetID.(type) {
+ case string:
+ return v
+ case float64:
+ return fmt.Sprintf("%.0f", v)
+ case int:
+ return fmt.Sprintf("%d", v)
+ default:
+ return fmt.Sprintf("%v", v)
+ }
+}
+
// FinalizeEpisodeRequest 完成剧集制作请求
type FinalizeEpisodeRequest struct {
EpisodeID string `json:"episode_id"`
@@ -405,32 +427,39 @@ func (s *VideoMergeService) FinalizeEpisode(episodeID string, timelineData *Fina
var skippedScenes []int
if timelineData != nil && len(timelineData.Clips) > 0 {
+ s.log.Infow("Processing timeline data", "clips_count", len(timelineData.Clips))
// 使用前端提供的时间线数据
- for _, clip := range timelineData.Clips {
+ for i, clip := range timelineData.Clips {
+ assetIDStr := getAssetIDString(clip.AssetID)
+ s.log.Infow("Processing clip", "index", i, "storyboard_id", clip.StoryboardID, "asset_id", assetIDStr, "order", clip.Order)
// 优先使用素材库中的视频(通过AssetID)
var videoURL string
var sceneID uint
- if clip.AssetID != "" {
+ if assetIDStr != "" {
// 从素材库获取视频,优先使用 local_path
var asset models.Asset
- if err := s.db.Where("id = ? AND type = ?", clip.AssetID, models.AssetTypeVideo).First(&asset).Error; err == nil {
- // 优先使用 local_path(本地文件)
+ if err := s.db.Where("id = ? AND type = ?", assetIDStr, models.AssetTypeVideo).First(&asset).Error; err == nil {
+ // 优先使用 local_path
if asset.LocalPath != nil && *asset.LocalPath != "" {
- // 构建完整的本地路径
- videoURL = filepath.Join(s.storagePath, *asset.LocalPath)
- s.log.Infow("Using local video from asset library", "asset_id", clip.AssetID, "local_path", videoURL)
+ // 检查是否已经是完整路径
+ if filepath.IsAbs(*asset.LocalPath) || filepath.HasPrefix(*asset.LocalPath, s.storagePath) {
+ videoURL = *asset.LocalPath
+ } else {
+ videoURL = filepath.Join(s.storagePath, *asset.LocalPath)
+ }
+ s.log.Infow("Using local video from asset library", "asset_id", assetIDStr, "local_path", videoURL)
} else {
// 回退到远程 URL
videoURL = asset.URL
- s.log.Infow("Using remote video from asset library", "asset_id", clip.AssetID, "video_url", videoURL)
+ s.log.Infow("Using remote video from asset library", "asset_id", assetIDStr, "video_url", videoURL)
}
// 如果asset关联了storyboard,使用关联的storyboard_id
if asset.StoryboardID != nil {
sceneID = *asset.StoryboardID
}
} else {
- s.log.Warnw("Asset not found, will try storyboard video", "asset_id", clip.AssetID, "error", err)
+ s.log.Warnw("Asset not found, will try storyboard video", "asset_id", assetIDStr, "error", err)
}
}
@@ -446,8 +475,12 @@ func (s *VideoMergeService) FinalizeEpisode(episodeID string, timelineData *Fina
var videoGen models.VideoGeneration
if err := s.db.Where("storyboard_id = ? AND status = ?", scene.ID, "completed").Order("created_at DESC").First(&videoGen).Error; err == nil {
if videoGen.LocalPath != nil && *videoGen.LocalPath != "" {
- // 使用本地路径
- videoURL = filepath.Join(s.storagePath, *videoGen.LocalPath)
+ // 检查是否已经是完整路径
+ if filepath.IsAbs(*videoGen.LocalPath) || filepath.HasPrefix(*videoGen.LocalPath, s.storagePath) {
+ videoURL = *videoGen.LocalPath
+ } else {
+ videoURL = filepath.Join(s.storagePath, *videoGen.LocalPath)
+ }
sceneID = scene.ID
s.log.Infow("Using local video from video_generation", "storyboard_id", clip.StoryboardID, "local_path", videoURL)
} else if scene.VideoURL != nil && *scene.VideoURL != "" {
@@ -487,8 +520,10 @@ func (s *VideoMergeService) FinalizeEpisode(episodeID string, timelineData *Fina
s.log.Infow("Adding scene clip with transition",
"scene_id", sceneID,
"order", clip.Order,
+ "video_url", videoURL,
"transition", clip.Transition)
sceneClips = append(sceneClips, sceneClip)
+ s.log.Infow("Scene clip added", "total_clips", len(sceneClips))
}
} else {
// 没有时间线数据,使用默认场景顺序
@@ -507,7 +542,12 @@ func (s *VideoMergeService) FinalizeEpisode(episodeID string, timelineData *Fina
First(&asset).Error; err == nil {
// 优先使用 local_path
if asset.LocalPath != nil && *asset.LocalPath != "" {
- videoURL = filepath.Join(s.storagePath, *asset.LocalPath)
+ // 检查是否已经是完整路径
+ if filepath.IsAbs(*asset.LocalPath) || filepath.HasPrefix(*asset.LocalPath, s.storagePath) {
+ videoURL = *asset.LocalPath
+ } else {
+ videoURL = filepath.Join(s.storagePath, *asset.LocalPath)
+ }
s.log.Infow("Using local video from asset library for storyboard",
"storyboard_id", scene.ID,
"asset_id", asset.ID,
@@ -524,7 +564,12 @@ func (s *VideoMergeService) FinalizeEpisode(episodeID string, timelineData *Fina
var videoGen models.VideoGeneration
if err := s.db.Where("storyboard_id = ? AND status = ?", scene.ID, "completed").Order("created_at DESC").First(&videoGen).Error; err == nil {
if videoGen.LocalPath != nil && *videoGen.LocalPath != "" {
- videoURL = filepath.Join(s.storagePath, *videoGen.LocalPath)
+ // 检查是否已经是完整路径
+ if filepath.IsAbs(*videoGen.LocalPath) || filepath.HasPrefix(*videoGen.LocalPath, s.storagePath) {
+ videoURL = *videoGen.LocalPath
+ } else {
+ videoURL = filepath.Join(s.storagePath, *videoGen.LocalPath)
+ }
s.log.Infow("Using local video from video_generation for storyboard",
"storyboard_id", scene.ID,
"local_path", videoURL)
diff --git a/data/drama.db b/data/drama.db
new file mode 100644
index 0000000..e69de29
diff --git a/infrastructure/external/ffmpeg/ffmpeg.go b/infrastructure/external/ffmpeg/ffmpeg.go
index 3692dd6..9a54bd4 100644
--- a/infrastructure/external/ffmpeg/ffmpeg.go
+++ b/infrastructure/external/ffmpeg/ffmpeg.go
@@ -109,8 +109,26 @@ func (f *FFmpeg) downloadVideo(url, destPath string) (string, error) {
if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") {
// 这是本地文件路径,检查文件是否存在
if _, err := os.Stat(url); err == nil {
- f.log.Infow("Using local video file", "path", url)
- return url, nil
+ f.log.Infow("Copying local video file to temp", "source", url, "dest", destPath)
+ // 复制本地文件到临时目录,避免删除原始文件
+ sourceFile, err := os.Open(url)
+ if err != nil {
+ return "", fmt.Errorf("failed to open source file: %w", err)
+ }
+ defer sourceFile.Close()
+
+ destFile, err := os.Create(destPath)
+ if err != nil {
+ return "", fmt.Errorf("failed to create dest file: %w", err)
+ }
+ defer destFile.Close()
+
+ _, err = io.Copy(destFile, sourceFile)
+ if err != nil {
+ return "", fmt.Errorf("failed to copy file: %w", err)
+ }
+
+ return destPath, nil
} else {
return "", fmt.Errorf("local file not found: %s", url)
}
diff --git a/web/src/components/editor/VideoTimelineEditor.vue b/web/src/components/editor/VideoTimelineEditor.vue
index efafa08..07da388 100644
--- a/web/src/components/editor/VideoTimelineEditor.vue
+++ b/web/src/components/editor/VideoTimelineEditor.vue
@@ -4,20 +4,29 @@
<div class="editor-toolbar">
<div class="toolbar-left">
<el-button-group>
- <el-button :icon="VideoPlay" @click="playTimeline" :disabled="timelineClips.length === 0">{{ $t('common.play') }}</el-button>
- <el-button :icon="VideoPause" @click="pauseTimeline">{{ $t('common.pause') }}</el-button>
+ <el-button
+ :icon="VideoPlay"
+ @click="playTimeline"
+ :disabled="timelineClips.length === 0"
+ >{{ $t("common.play") }}</el-button
+ >
+ <el-button :icon="VideoPause" @click="pauseTimeline">{{
+ $t("common.pause")
+ }}</el-button>
</el-button-group>
- <span class="time-display">{{ formatTime(currentTime) }} / {{ formatTime(totalDuration) }}</span>
+ <span class="time-display"
+ >{{ formatTime(currentTime) }} / {{ formatTime(totalDuration) }}</span
+ >
</div>
<div class="toolbar-right">
- <el-button
- type="primary"
+ <el-button
+ type="primary"
:icon="VideoCamera"
@click="submitTimelineForMerge"
:disabled="timelineClips.length === 0"
:loading="serverMerging"
>
- {{ $t('video.merge') }}
+ {{ $t("video.merge") }}
</el-button>
</div>
</div>
@@ -27,7 +36,7 @@
<!-- 预览区域 -->
<div class="preview-panel">
<div class="video-preview" @click="togglePlay">
- <video
+ <video
ref="previewPlayer"
:src="currentPreviewUrl"
@loadedmetadata="handlePreviewLoaded"
@@ -35,22 +44,32 @@
@ended="handlePreviewEnded"
/>
<!-- 音频播放器(隐藏) -->
- <audio
+ <audio
ref="audioPlayer"
:src="currentAudioUrl"
@loadedmetadata="handleAudioLoaded"
@ended="handleAudioEnded"
- style="display: none;"
+ style="display: none"
/>
<!-- 转场效果层 -->
- <div
+ <div
v-if="transitionState.active"
class="transition-overlay"
- :class="[`transition-${transitionState.type}`, { 'transition-in': transitionState.phase === 'in', 'transition-out': transitionState.phase === 'out' }]"
+ :class="[
+ `transition-${transitionState.type}`,
+ {
+ 'transition-in': transitionState.phase === 'in',
+ 'transition-out': transitionState.phase === 'out',
+ },
+ ]"
:style="{ animationDuration: transitionState.duration + 's' }"
></div>
<!-- 播放/暂停图标覆盖层 -->
- <div class="video-play-overlay" :class="{ hidden: isPlaying }" v-if="currentPreviewUrl">
+ <div
+ class="video-play-overlay"
+ :class="{ hidden: isPlaying }"
+ v-if="currentPreviewUrl"
+ >
<el-icon :size="64"><VideoPlay /></el-icon>
</div>
<div class="preview-overlay" v-if="!currentPreviewUrl">
@@ -58,8 +77,8 @@
</div>
</div>
<div class="preview-controls">
- <el-slider
- v-model="currentTime"
+ <el-slider
+ v-model="currentTime"
:max="totalDuration"
:step="0.1"
@change="seekToTime"
@@ -71,17 +90,19 @@
<div class="media-library">
<div class="library-header">
<div class="header-left">
- <h4>{{ $t('video.mediaLibrary') }}</h4>
- <span>{{ $t('video.videoCount', { count: availableStoryboards.length }) }}</span>
+ <h4>{{ $t("video.mediaLibrary") }}</h4>
+ <span>{{
+ $t("video.videoCount", { count: availableStoryboards.length })
+ }}</span>
</div>
- <el-button
- type="primary"
+ <el-button
+ type="primary"
size="small"
:icon="FolderAdd"
@click="addAllScenesInOrder"
:disabled="availableStoryboards.length === 0"
>
- {{ $t('common.addAll') }}
+ {{ $t("common.addAll") }}
</el-button>
</div>
<div class="media-grid">
@@ -94,28 +115,34 @@
>
<div class="media-thumbnail" @click="previewScene(scene)">
<video :src="scene.video_url" />
- <div class="media-duration">{{ scene.duration > 0 ? scene.duration.toFixed(1) : '?' }}s</div>
- <el-button
+ <div class="media-duration">
+ {{ scene.duration > 0 ? scene.duration.toFixed(1) : "?" }}s
+ </div>
+ <el-button
class="delete-btn"
- type="danger"
- size="small"
+ type="danger"
+ size="small"
:icon="Delete"
circle
@click.stop="deleteAsset(scene)"
/>
<div class="media-overlay">
- <el-button
- type="primary"
- size="small"
+ <el-button
+ type="primary"
+ size="small"
:icon="Plus"
@click.stop="addClipToTimeline(scene)"
>
- {{ $t('common.addToTimeline') }}
+ {{ $t("common.addToTimeline") }}
</el-button>
</div>
</div>
<div class="media-info">
- <div class="media-title">{{ $t('storyboard.shot') }} #{{ scene.storyboard_num || scene.assetId }}</div>
+ <div class="media-title">
+ {{ $t("storyboard.shot") }} #{{
+ scene.storyboard_num || scene.asset_id
+ }}
+ </div>
</div>
</div>
</div>
@@ -128,7 +155,7 @@
<div class="zoom-controls">
<el-button-group size="small">
<el-button @click="zoomOut">-</el-button>
- <el-button @click="zoomReset">{{ $t('common.reset') }}</el-button>
+ <el-button @click="zoomReset">{{ $t("common.reset") }}</el-button>
<el-button @click="zoomIn">+</el-button>
</el-button-group>
<span class="zoom-level">{{ Math.round(zoom * 100) }}%</span>
@@ -138,28 +165,27 @@
<div class="timeline-container" ref="timelineContainer">
<!-- 时间标尺 -->
<div class="timeline-ruler" :style="{ width: timelineWidth + 'px' }">
- <div
- v-for="tick in timeRulerTicks"
+ <div
+ v-for="tick in timeRulerTicks"
:key="tick.time"
class="ruler-tick"
:style="{ left: tick.position + 'px' }"
>
<div class="tick-mark" :class="tick.type"></div>
- <div class="tick-label" v-if="tick.type === 'major'">{{ formatTime(tick.time) }}</div>
+ <div class="tick-label" v-if="tick.type === 'major'">
+ {{ formatTime(tick.time) }}
+ </div>
</div>
</div>
<!-- 播放头 -->
- <div
- class="playhead"
- :style="{ left: playheadPosition + 'px' }"
- >
+ <div class="playhead" :style="{ left: playheadPosition + 'px' }">
<div class="playhead-line"></div>
<div class="playhead-handle"></div>
</div>
<!-- 视频轨道 -->
- <div
+ <div
class="timeline-track"
:style="{ width: timelineWidth + 'px' }"
@drop="handleTrackDrop($event)"
@@ -167,10 +193,10 @@
@click="clickTimeline($event)"
>
<div class="track-label">
- <span>{{ $t('video.videoTrack') }}</span>
- <el-button
- type="text"
- size="small"
+ <span>{{ $t("video.videoTrack") }}</span>
+ <el-button
+ type="text"
+ size="small"
@click.stop="clearAllClips"
:disabled="timelineClips.length === 0"
:title="$t('video.clearTrack')"
@@ -194,17 +220,27 @@
<video :src="clip.video_url" />
</div>
<div class="clip-info">
- <div class="clip-title">{{ $t('storyboard.scene') }} {{ clip.storyboard_number }}</div>
- <div class="clip-duration">{{ clip.duration.toFixed(1) }}s</div>
+ <div class="clip-title">
+ {{ $t("storyboard.scene") }} {{ clip.storyboard_number }}
+ </div>
+ <div class="clip-duration">
+ {{ clip.duration.toFixed(1) }}s
+ </div>
</div>
</div>
- <div class="clip-resize-left" @mousedown.stop="startResizeClip($event, clip, 'left')"></div>
- <div class="clip-resize-right" @mousedown.stop="startResizeClip($event, clip, 'right')"></div>
+ <div
+ class="clip-resize-left"
+ @mousedown.stop="startResizeClip($event, clip, 'left')"
+ ></div>
+ <div
+ class="clip-resize-right"
+ @mousedown.stop="startResizeClip($event, clip, 'right')"
+ ></div>
<div class="clip-remove" @click.stop="removeClip(clip)">
<el-icon><Close /></el-icon>
</div>
</div>
-
+
<!-- 转场指示器 -->
<div
v-for="(clip, index) in timelineClips.slice(1)"
@@ -214,26 +250,28 @@
@click.stop="openTransitionDialog(timelineClips[index])"
>
<el-icon><connection /></el-icon>
- <span class="transition-label">{{ getTransitionLabel(timelineClips[index]) }}</span>
+ <span class="transition-label">{{
+ getTransitionLabel(timelineClips[index])
+ }}</span>
</div>
</div>
</div>
<!-- 音频轨道 -->
- <div
+ <div
v-if="showAudioTrack"
class="timeline-track audio-track"
:style="{ width: timelineWidth + 'px' }"
@click="clickTimeline($event)"
>
<div class="track-label">
- <span>{{ $t('video.audioTrack') }}</span>
- <el-button
- type="text"
- size="small"
+ <span>{{ $t("video.audioTrack") }}</span>
+ <el-button
+ type="text"
+ size="small"
@click.stop="extractAllAudio"
:disabled="timelineClips.length === 0"
-:title="$t('video.extractAudio')"
+ :title="$t('video.extractAudio')"
>
<el-icon><Headset /></el-icon>
</el-button>
@@ -254,12 +292,22 @@
<el-icon><Microphone /></el-icon>
</div>
<div class="clip-info">
- <div class="clip-title">{{ $t('video.audio') }} {{ audio.order + 1 }}</div>
- <div class="clip-duration">{{ audio.duration.toFixed(1) }}s</div>
+ <div class="clip-title">
+ {{ $t("video.audio") }} {{ audio.order + 1 }}
+ </div>
+ <div class="clip-duration">
+ {{ audio.duration.toFixed(1) }}s
+ </div>
</div>
</div>
- <div class="clip-resize-left" @mousedown.stop="startResizeAudioClip($event, audio, 'left')"></div>
- <div class="clip-resize-right" @mousedown.stop="startResizeAudioClip($event, audio, 'right')"></div>
+ <div
+ class="clip-resize-left"
+ @mousedown.stop="startResizeAudioClip($event, audio, 'left')"
+ ></div>
+ <div
+ class="clip-resize-right"
+ @mousedown.stop="startResizeAudioClip($event, audio, 'right')"
+ ></div>
<div class="clip-remove" @click.stop="removeAudioClip(audio)">
<el-icon><Close /></el-icon>
</div>
@@ -277,7 +325,10 @@
>
<el-form label-width="100px">
<el-form-item :label="$t('video.transitionType')">
- <el-select v-model="editingTransition.type" :placeholder="$t('video.selectTransition')">
+ <el-select
+ v-model="editingTransition.type"
+ :placeholder="$t('video.selectTransition')"
+ >
<el-option label="无转场" value="none" />
<!-- 淡入淡出类 -->
<el-option label="淡入淡出" value="fade" />
@@ -306,7 +357,10 @@
<el-option label="垂直关闭" value="vertclose" />
</el-select>
</el-form-item>
- <el-form-item :label="$t('video.transitionDuration')" v-if="editingTransition.type !== 'none'">
+ <el-form-item
+ :label="$t('video.transitionDuration')"
+ v-if="editingTransition.type !== 'none'"
+ >
<el-slider
v-model="editingTransition.duration"
:min="0.3"
@@ -331,9 +385,9 @@
</el-dialog>
<!-- 合并进度对话框 -->
- <el-dialog
- v-model="mergeDialogVisible"
- title="视频合并中"
+ <el-dialog
+ v-model="mergeDialogVisible"
+ title="视频合并中"
width="500px"
:close-on-click-modal="false"
:close-on-press-escape="false"
@@ -348,13 +402,15 @@
</div>
<div class="progress-message">{{ mergeProgressDetail.message }}</div>
</div>
-
- <el-progress
- :percentage="mergeProgressDetail.progress"
- :status="mergeProgressDetail.phase === 'completed' ? 'success' : undefined"
+
+ <el-progress
+ :percentage="mergeProgressDetail.progress"
+ :status="
+ mergeProgressDetail.phase === 'completed' ? 'success' : undefined
+ "
:stroke-width="20"
/>
-
+
<div class="progress-tips">
<p v-if="mergeProgressDetail.phase === 'loading'">
<el-icon><Loading /></el-icon>
@@ -374,7 +430,7 @@
</p>
</div>
</div>
-
+
<template #footer v-if="!merging">
<el-button @click="mergeDialogVisible = false">关闭</el-button>
</template>
@@ -383,78 +439,119 @@
</template>
<script setup lang="ts">
-import { ref, computed, onMounted, onUnmounted } from 'vue'
-import { ElMessage, ElMessageBox } from 'element-plus'
-import {
- VideoPlay, VideoPause, Plus, FolderAdd, ArrowLeft, ArrowRight,
- Scissor, Connection, Setting, ZoomIn, ZoomOut, Refresh, Download, Delete,
- Close, VideoCamera, Check, Loading, Headset, Microphone
-} from '@element-plus/icons-vue'
-import { videoMerger, type MergeProgress } from '@/utils/videoMerger'
-import { trimAndMergeVideos } from '@/utils/ffmpeg'
-import { getVideoUrl } from '@/utils/image'
+import { ref, computed, onMounted, onUnmounted } from "vue";
+import { ElMessage, ElMessageBox } from "element-plus";
+import {
+ VideoPlay,
+ VideoPause,
+ Plus,
+ FolderAdd,
+ ArrowLeft,
+ ArrowRight,
+ Scissor,
+ Connection,
+ Setting,
+ ZoomIn,
+ ZoomOut,
+ Refresh,
+ Download,
+ Delete,
+ Close,
+ VideoCamera,
+ Check,
+ Loading,
+ Headset,
+ Microphone,
+} from "@element-plus/icons-vue";
+import { videoMerger, type MergeProgress } from "@/utils/videoMerger";
+import { trimAndMergeVideos } from "@/utils/ffmpeg";
+import { getVideoUrl } from "@/utils/image";
interface Scene {
- id: string
- storyboard_number: number
- title?: string
- description?: string
- location?: string
- time?: string
- video_url: string
- duration?: number
+ id: string;
+ storyboard_id: string;
+ storyboard_number: number;
+ title?: string;
+ description?: string;
+ location?: string;
+ time?: string;
+ video_url: string;
+ asset_id?: string;
+ duration?: number;
}
interface TimelineClip {
- id: string
- storyboard_id: string
- storyboard_number: number
- video_url: string
- start_time: number
- end_time: number
- duration: number
- position: number // 在时间线上的位置(秒)
- order: number
+ id: string;
+ storyboard_id: string;
+ storyboard_number: number;
+ video_url: string;
+ asset_id?: string; // 素材库中的资源ID
+ start_time: number;
+ end_time: number;
+ duration: number;
+ position: number; // 在时间线上的位置(秒)
+ order: number;
transition?: {
- type: 'fade' | 'fadeblack' | 'fadewhite' | 'fadegrays' | 'slideleft' | 'slideright' | 'slideup' | 'slidedown' | 'wipeleft' | 'wiperight' | 'wipeup' | 'wipedown' | 'circleopen' | 'circleclose' | 'dissolve' | 'distance' | 'horzopen' | 'horzclose' | 'vertopen' | 'vertclose' | 'none'
- duration: number
- }
- audio_url?: string // 提取的音频URL
- muted?: boolean // 是否静音
+ type:
+ | "fade"
+ | "fadeblack"
+ | "fadewhite"
+ | "fadegrays"
+ | "slideleft"
+ | "slideright"
+ | "slideup"
+ | "slidedown"
+ | "wipeleft"
+ | "wiperight"
+ | "wipeup"
+ | "wipedown"
+ | "circleopen"
+ | "circleclose"
+ | "dissolve"
+ | "distance"
+ | "horzopen"
+ | "horzclose"
+ | "vertopen"
+ | "vertclose"
+ | "none";
+ duration: number;
+ };
+ audio_url?: string; // 提取的音频URL
+ muted?: boolean; // 是否静音
}
interface AudioClip {
- id: string
- source_clip_id: string // 关联的视频片段ID
- audio_url: string
- start_time: number
- end_time: number
- duration: number
- position: number
- order: number
- volume: number // 音量 0-1
+ id: string;
+ source_clip_id: string; // 关联的视频片段ID
+ audio_url: string;
+ start_time: number;
+ end_time: number;
+ duration: number;
+ position: number;
+ order: number;
+ volume: number; // 音量 0-1
}
const props = defineProps<{
- scenes: Scene[]
- episodeId: string
- dramaId: string
- assets?: any[]
-}>()
+ scenes: Scene[];
+ episodeId: string;
+ dramaId: string;
+ assets?: any[];
+}>();
const emit = defineEmits<{
- (e: 'merge-completed', mergeId: number): void
- (e: 'asset-deleted'): void
-}>()
+ (e: "merge-completed", mergeId: number): void;
+ (e: "asset-deleted"): void;
+}>();
// 基础状态
const availableStoryboards = computed(() => {
const assets = (props.assets || [])
- .filter(a => {
- const isValid = a.type === 'video' && a.url
- return isValid
+ .filter((a) => {
+ const isValid = a.type === "video" && a.url;
+ return isValid;
})
- .map(a => ({
+ .map((a) => ({
id: `asset_${a.id}`,
storyboard_number: a.storyboard_num || a.id,
storyboard_num: a.storyboard_num,
@@ -463,658 +560,717 @@ const availableStoryboards = computed(() => {
duration: a.duration || 0,
name: a.name,
isAsset: true,
- assetId: a.id
+ asset_id: a.id, // 使用 asset_id 字段名
}))
.sort((a, b) => {
// 优先按storyboard_num排序,如果没有则按storyboard_id排序,最后按asset id排序
- const aNum = a.storyboard_num || a.storyboard_id || a.assetId
- const bNum = b.storyboard_num || b.storyboard_id || b.assetId
- return aNum - bNum
- })
- return assets
-})
-const timelineClips = ref<TimelineClip[]>([])
-const audioClips = ref<AudioClip[]>([])
-const selectedClipId = ref<string | null>(null)
-const selectedAudioClipId = ref<string | null>(null)
-const previewPlayer = ref<HTMLVideoElement | null>(null)
-const audioPlayer = ref<HTMLAudioElement | null>(null)
-const timelineContainer = ref<HTMLElement | null>(null)
-const showAudioTrack = ref(true) // 是否显示音频轨道
+ const aNum = a.storyboard_num || a.storyboard_id || a.asset_id;
+ const bNum = b.storyboard_num || b.storyboard_id || b.asset_id;
+ return aNum - bNum;
+ });
+ return assets;
+});
+const timelineClips = ref<TimelineClip[]>([]);
+const audioClips = ref<AudioClip[]>([]);
+const selectedClipId = ref<string | null>(null);
+const selectedAudioClipId = ref<string | null>(null);
+const previewPlayer = ref<HTMLVideoElement | null>(null);
+const audioPlayer = ref<HTMLAudioElement | null>(null);
+const timelineContainer = ref<HTMLElement | null>(null);
+const showAudioTrack = ref(true); // 是否显示音频轨道
// 时间线状态
-const currentTime = ref(0)
-const zoom = ref(1) // 缩放级别
-const pixelsPerSecond = computed(() => 50 * zoom.value) // 每秒对应的像素数
-const isPlaying = ref(false)
-const playbackTimer = ref<number | null>(null)
+const currentTime = ref(0);
+const zoom = ref(1); // 缩放级别
+const pixelsPerSecond = computed(() => 50 * zoom.value); // 每秒对应的像素数
+const isPlaying = ref(false);
+const playbackTimer = ref<number | null>(null);
// 转场预览状态(必须在模板使用前定义)
const transitionState = ref({
active: false,
- type: 'fade',
- phase: 'in' as 'in' | 'out',
- duration: 1.0
-})
+ type: "fade",
+ phase: "in" as "in" | "out",
+ duration: 1.0,
+});
// 导出状态
-const merging = ref(false)
-const serverMerging = ref(false)
-const mergeProgress = ref(0)
-const mergeDialogVisible = ref(false)
+const merging = ref(false);
+const serverMerging = ref(false);
+const mergeProgress = ref(0);
+const mergeDialogVisible = ref(false);
const mergeProgressDetail = ref<MergeProgress>({
- phase: 'loading',
+ phase: "loading",
progress: 0,
- message: ''
-})
+ message: "",
+});
// 转场设置状态
-const transitionDialogVisible = ref(false)
-const editingTransitionClipId = ref<string | null>(null)
+const transitionDialogVisible = ref(false);
+const editingTransitionClipId = ref<string | null>(null);
const editingTransition = ref({
- type: 'fade' as 'fade' | 'fadeblack' | 'fadewhite' | 'fadegrays' | 'slideleft' | 'slideright' | 'slideup' | 'slidedown' | 'wipeleft' | 'wiperight' | 'wipeup' | 'wipedown' | 'circleopen' | 'circleclose' | 'dissolve' | 'distance' | 'horzopen' | 'horzclose' | 'vertopen' | 'vertclose' | 'none',
- duration: 1.0
-})
+ type: "fade" as
+ | "fade"
+ | "fadeblack"
+ | "fadewhite"
+ | "fadegrays"
+ | "slideleft"
+ | "slideright"
+ | "slideup"
+ | "slidedown"
+ | "wipeleft"
+ | "wiperight"
+ | "wipeup"
+ | "wipedown"
+ | "circleopen"
+ | "circleclose"
+ | "dissolve"
+ | "distance"
+ | "horzopen"
+ | "horzclose"
+ | "vertopen"
+ | "vertclose"
+ | "none",
+ duration: 1.0,
+});
// 计算总时长
const totalDuration = computed(() => {
- if (timelineClips.value.length === 0) return 0
- const lastClip = timelineClips.value[timelineClips.value.length - 1]
- return lastClip ? lastClip.position + lastClip.duration : 0
-})
+ if (timelineClips.value.length === 0) return 0;
+ const lastClip = timelineClips.value[timelineClips.value.length - 1];
+ return lastClip ? lastClip.position + lastClip.duration : 0;
+});
// 工具函数
const formatTime = (seconds: number) => {
- const mins = Math.floor(seconds / 60)
- const secs = Math.floor(seconds % 60)
- const ms = Math.floor((seconds % 1) * 10)
- return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}.${ms}`
-}
+ const mins = Math.floor(seconds / 60);
+ const secs = Math.floor(seconds % 60);
+ const ms = Math.floor((seconds % 1) * 10);
+ return `${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}.${ms}`;
+};
const getSceneDesc = (scene: Scene) => {
- const parts = []
- if (scene.location) parts.push(scene.location)
- if (scene.time) parts.push(scene.time)
- return parts.join(' · ') || (scene.description?.slice(0, 15) + '...' || '无描述')
-}
+ const parts = [];
+ if (scene.location) parts.push(scene.location);
+ if (scene.time) parts.push(scene.time);
+ return (
+ parts.join(" · ") || scene.description?.slice(0, 15) + "..." || "无描述"
+ );
+};
// 预览相关
const currentPreviewUrl = computed(() => {
- if (timelineClips.value.length === 0) return ''
+ if (timelineClips.value.length === 0) return "";
// 根据当前时间找到应该播放的片段
- const clip = timelineClips.value.find(c =>
- currentTime.value >= c.position && currentTime.value < c.position + c.duration
- )
- return clip?.video_url || timelineClips.value[0]?.video_url || ''
-})
+ const clip = timelineClips.value.find(
+ (c) =>
+ currentTime.value >= c.position &&
+ currentTime.value < c.position + c.duration,
+ );
+ return clip?.video_url || timelineClips.value[0]?.video_url || "";
+});
// 当前音频URL
const currentAudioUrl = computed(() => {
- if (audioClips.value.length === 0) return ''
+ if (audioClips.value.length === 0) return "";
// 根据当前时间找到应该播放的音频片段
- const audioClip = audioClips.value.find(a =>
- currentTime.value >= a.position && currentTime.value < a.position + a.duration
- )
- return audioClip?.audio_url || ''
-})
+ const audioClip = audioClips.value.find(
+ (a) =>
+ currentTime.value >= a.position &&
+ currentTime.value < a.position + a.duration,
+ );
+ return audioClip?.audio_url || "";
+});
const previewScene = (scene: Scene) => {
if (previewPlayer.value) {
- previewPlayer.value.src = scene.video_url
- previewPlayer.value.play()
+ previewPlayer.value.src = scene.video_url;
+ previewPlayer.value.play();
}
-}
+};
const handlePreviewLoaded = () => {
// 视频加载完成后跳转到正确的时间点
if (previewPlayer.value) {
- const clip = timelineClips.value.find(c =>
- currentTime.value >= c.position && currentTime.value < c.position + c.duration
- )
+ const clip = timelineClips.value.find(
+ (c) =>
+ currentTime.value >= c.position &&
+ currentTime.value < c.position + c.duration,
+ );
if (clip) {
- const offsetInClip = currentTime.value - clip.position
- previewPlayer.value.currentTime = clip.start_time + offsetInClip
+ const offsetInClip = currentTime.value - clip.position;
+ previewPlayer.value.currentTime = clip.start_time + offsetInClip;
}
}
-}
+};
const handleAudioLoaded = () => {
// 音频加载完成后跳转到正确的时间点
if (audioPlayer.value && audioClips.value.length > 0) {
- const audioClip = audioClips.value.find(a =>
- currentTime.value >= a.position && currentTime.value < a.position + a.duration
- )
+ const audioClip = audioClips.value.find(
+ (a) =>
+ currentTime.value >= a.position &&
+ currentTime.value < a.position + a.duration,
+ );
if (audioClip) {
- const offsetInClip = currentTime.value - audioClip.position
- audioPlayer.value.currentTime = audioClip.start_time + offsetInClip
+ const offsetInClip = currentTime.value - audioClip.position;
+ audioPlayer.value.currentTime = audioClip.start_time + offsetInClip;
}
}
-}
+};
const handleAudioEnded = () => {
// 音频自然结束,尝试播放下一个音频片段
- const currentAudio = audioClips.value.find(a =>
- currentTime.value >= a.position && currentTime.value < a.position + a.duration
- )
-
+ const currentAudio = audioClips.value.find(
+ (a) =>
+ currentTime.value >= a.position &&
+ currentTime.value < a.position + a.duration,
+ );
+
if (currentAudio) {
- const currentIndex = audioClips.value.findIndex(a => a.id === currentAudio.id)
- const nextAudio = audioClips.value[currentIndex + 1]
-
+ const currentIndex = audioClips.value.findIndex(
+ (a) => a.id === currentAudio.id,
+ );
+ const nextAudio = audioClips.value[currentIndex + 1];
+
if (nextAudio && isPlaying.value) {
// 有下一个音频片段且正在播放,继续
// 时间线会自动更新到下一个片段
}
}
-}
+};
const handlePreviewTimeUpdate = () => {
- if (!isPlaying.value || !previewPlayer.value) return
-
+ if (!isPlaying.value || !previewPlayer.value) return;
+
// 找到当前播放的片段
- const currentClip = timelineClips.value.find(c =>
- currentTime.value >= c.position && currentTime.value < c.position + c.duration
- )
-
+ const currentClip = timelineClips.value.find(
+ (c) =>
+ currentTime.value >= c.position &&
+ currentTime.value < c.position + c.duration,
+ );
+
if (!currentClip) {
- pauseTimeline()
- return
+ pauseTimeline();
+ return;
}
-
+
// 计算时间线上的当前位置
- const videoTime = previewPlayer.value.currentTime
- const clipOffset = videoTime - currentClip.start_time
- currentTime.value = currentClip.position + clipOffset
-
+ const videoTime = previewPlayer.value.currentTime;
+ const clipOffset = videoTime - currentClip.start_time;
+ currentTime.value = currentClip.position + clipOffset;
+
// 检查是否播放到片段结尾(提前0.1秒检测,避免播放完才切换)
if (videoTime >= currentClip.end_time - 0.1) {
// 查找下一个片段
- const currentIndex = timelineClips.value.findIndex(c => c.id === currentClip.id)
- const nextClip = timelineClips.value[currentIndex + 1]
-
+ const currentIndex = timelineClips.value.findIndex(
+ (c) => c.id === currentClip.id,
+ );
+ const nextClip = timelineClips.value[currentIndex + 1];
+
if (nextClip) {
// 切换到下一个片段
- switchToClip(nextClip)
+ switchToClip(nextClip);
} else {
// 没有下一个片段,停止播放
- pauseTimeline()
- currentTime.value = totalDuration.value
+ pauseTimeline();
+ currentTime.value = totalDuration.value;
}
}
-}
+};
const switchToClip = async (clip: TimelineClip) => {
- if (!previewPlayer.value) return
-
+ if (!previewPlayer.value) return;
+
// 获取转场配置
- const transition = clip.transition
- const hasTransition = transition && transition.type !== 'none'
- const transitionDuration = hasTransition ? (transition.duration * 1000) : 0
-
+ const transition = clip.transition;
+ const hasTransition = transition && transition.type !== "none";
+ const transitionDuration = hasTransition ? transition.duration * 1000 : 0;
+
if (hasTransition) {
// 触发转场效果
transitionState.value = {
active: true,
type: transition.type,
- phase: 'out',
- duration: transition.duration
- }
-
+ phase: "out",
+ duration: transition.duration,
+ };
+
// 等待转场动画完成一半
- await new Promise(resolve => setTimeout(resolve, transitionDuration / 2))
+ await new Promise((resolve) => setTimeout(resolve, transitionDuration / 2));
}
-
+
// 暂停当前播放,避免冲突
- previewPlayer.value.pause()
+ previewPlayer.value.pause();
if (audioPlayer.value) {
- audioPlayer.value.pause()
+ audioPlayer.value.pause();
}
-
+
// 切换视频源
- currentTime.value = clip.position
- previewPlayer.value.src = clip.video_url
-
+ currentTime.value = clip.position;
+ previewPlayer.value.src = clip.video_url;
+
// 同步切换音频源
if (audioClips.value.length > 0 && audioPlayer.value) {
- const audioClip = audioClips.value.find(a =>
- clip.position >= a.position && clip.position < a.position + a.duration
- )
+ const audioClip = audioClips.value.find(
+ (a) =>
+ clip.position >= a.position && clip.position < a.position + a.duration,
+ );
if (audioClip) {
- audioPlayer.value.src = audioClip.audio_url
+ audioPlayer.value.src = audioClip.audio_url;
}
}
-
+
// 等待视频加载
try {
await new Promise((resolve, reject) => {
- if (!previewPlayer.value) return reject()
-
+ if (!previewPlayer.value) return reject();
+
const onCanPlay = () => {
- previewPlayer.value?.removeEventListener('canplay', onCanPlay)
- previewPlayer.value?.removeEventListener('error', onError)
- resolve(undefined)
- }
-
+ previewPlayer.value?.removeEventListener("canplay", onCanPlay);
+ previewPlayer.value?.removeEventListener("error", onError);
+ resolve(undefined);
+ };
+
const onError = () => {
- previewPlayer.value?.removeEventListener('canplay', onCanPlay)
- previewPlayer.value?.removeEventListener('error', onError)
- reject()
- }
-
- previewPlayer.value.addEventListener('canplay', onCanPlay)
- previewPlayer.value.addEventListener('error', onError)
- })
-
+ previewPlayer.value?.removeEventListener("canplay", onCanPlay);
+ previewPlayer.value?.removeEventListener("error", onError);
+ reject();
+ };
+
+ previewPlayer.value.addEventListener("canplay", onCanPlay);
+ previewPlayer.value.addEventListener("error", onError);
+ });
+
// 设置起始时间并播放
- previewPlayer.value.currentTime = clip.start_time
-
+ previewPlayer.value.currentTime = clip.start_time;
+
if (hasTransition) {
// 切换到转场入场阶段
- transitionState.value.phase = 'in'
-
+ transitionState.value.phase = "in";
+
// 等待转场剩余时间
setTimeout(() => {
- transitionState.value.active = false
- }, transitionDuration / 2)
+ transitionState.value.active = false;
+ }, transitionDuration / 2);
}
-
+
if (isPlaying.value) {
- await previewPlayer.value.play()
-
+ await previewPlayer.value.play();
+
// 同步播放音频
if (audioClips.value.length > 0 && audioPlayer.value) {
- const audioClip = audioClips.value.find(a =>
- clip.position >= a.position && clip.position < a.position + a.duration
- )
+ const audioClip = audioClips.value.find(
+ (a) =>
+ clip.position >= a.position &&
+ clip.position < a.position + a.duration,
+ );
if (audioClip && audioPlayer.value.src) {
- audioPlayer.value.currentTime = audioClip.start_time
- audioPlayer.value.play().catch(err => {
- console.warn('音频播放失败:', err)
- })
+ audioPlayer.value.currentTime = audioClip.start_time;
+ audioPlayer.value.play().catch((err) => {
+ console.warn("音频播放失败:", err);
+ });
}
}
}
} catch (error) {
- console.error('切换视频片段失败:', error)
- transitionState.value.active = false
- pauseTimeline()
+ console.error("切换视频片段失败:", error);
+ transitionState.value.active = false;
+ pauseTimeline();
}
-}
+};
const handlePreviewEnded = () => {
// 视频自然结束,尝试播放下一个片段
- const currentClip = timelineClips.value.find(c =>
- currentTime.value >= c.position && currentTime.value < c.position + c.duration
- )
-
+ const currentClip = timelineClips.value.find(
+ (c) =>
+ currentTime.value >= c.position &&
+ currentTime.value < c.position + c.duration,
+ );
+
if (currentClip) {
- const currentIndex = timelineClips.value.findIndex(c => c.id === currentClip.id)
- const nextClip = timelineClips.value[currentIndex + 1]
-
+ const currentIndex = timelineClips.value.findIndex(
+ (c) => c.id === currentClip.id,
+ );
+ const nextClip = timelineClips.value[currentIndex + 1];
+
if (nextClip) {
- currentTime.value = nextClip.position
- seekToTime(nextClip.position)
+ currentTime.value = nextClip.position;
+ seekToTime(nextClip.position);
} else {
- pauseTimeline()
+ pauseTimeline();
}
}
-}
+};
// 时间线计算
const timelineWidth = computed(() => {
- const duration = Math.max(totalDuration.value, 30)
- const contentWidth = duration * pixelsPerSecond.value
- const minContentWidth = 800 // 最小内容宽度
- return 100 + Math.max(contentWidth, minContentWidth) + 100 // 100px左边距 + 100px右边距
-})
+ const duration = Math.max(totalDuration.value, 30);
+ const contentWidth = duration * pixelsPerSecond.value;
+ const minContentWidth = 800; // 最小内容宽度
+ return 100 + Math.max(contentWidth, minContentWidth) + 100; // 100px左边距 + 100px右边距
+});
const playheadPosition = computed(() => {
- return 100 + currentTime.value * pixelsPerSecond.value
-})
+ return 100 + currentTime.value * pixelsPerSecond.value;
+});
const timeRulerTicks = computed(() => {
- const ticks = []
- const duration = Math.max(totalDuration.value, 30)
- const interval = zoom.value >= 1.5 ? 1 : zoom.value >= 0.5 ? 5 : 10
-
+ const ticks = [];
+ const duration = Math.max(totalDuration.value, 30);
+ const interval = zoom.value >= 1.5 ? 1 : zoom.value >= 0.5 ? 5 : 10;
+
for (let i = 0; i <= duration; i += interval) {
ticks.push({
time: i,
position: 100 + i * pixelsPerSecond.value,
- type: i % (interval * 2) === 0 ? 'major' : 'minor'
- })
+ type: i % (interval * 2) === 0 ? "major" : "minor",
+ });
}
- return ticks
-})
+ return ticks;
+});
// 片段样式计算
const getClipStyle = (clip: TimelineClip) => {
return {
- left: 100 + clip.position * pixelsPerSecond.value + 'px',
- width: clip.duration * pixelsPerSecond.value + 'px'
- }
-}
+ left: 100 + clip.position * pixelsPerSecond.value + "px",
+ width: clip.duration * pixelsPerSecond.value + "px",
+ };
+};
// 拖拽场景到时间线
const handleDragStart = (event: DragEvent, scene: Scene) => {
if (event.dataTransfer) {
- event.dataTransfer.effectAllowed = 'copy'
- event.dataTransfer.setData('scene', JSON.stringify(scene))
+ event.dataTransfer.effectAllowed = "copy";
+ event.dataTransfer.setData("scene", JSON.stringify(scene));
}
-}
+};
const handleTrackDrop = (event: DragEvent) => {
- event.preventDefault()
- const sceneData = event.dataTransfer?.getData('scene')
- if (!sceneData) return
-
- const scene = JSON.parse(sceneData) as Scene
-
+ event.preventDefault();
+ const sceneData = event.dataTransfer?.getData("scene");
+ if (!sceneData) return;
+
+ const scene = JSON.parse(sceneData) as Scene;
+
// 默认添加到末尾,不使用拖拽位置(避免产生空隙)
- addClipToTimeline(scene)
-}
+ addClipToTimeline(scene);
+};
const getVideoDuration = (videoUrl: string): Promise<number> => {
return new Promise((resolve, reject) => {
- const video = document.createElement('video')
- video.preload = 'metadata'
- video.src = videoUrl
-
+ const video = document.createElement("video");
+ video.preload = "metadata";
+ video.src = videoUrl;
+
video.onloadedmetadata = () => {
- const duration = video.duration
- video.remove()
- resolve(duration)
- }
-
+ const duration = video.duration;
+ video.remove();
+ resolve(duration);
+ };
+
video.onerror = () => {
- video.remove()
- reject(new Error('Failed to load video'))
- }
- })
-}
+ video.remove();
+ reject(new Error("Failed to load video"));
+ };
+ });
+};
const addClipToTimeline = async (scene: Scene, insertAtPosition?: number) => {
// 获取视频真实时长
- let videoDuration = scene.duration || 5
+ let videoDuration = scene.duration || 5;
if (scene.video_url) {
try {
- videoDuration = await getVideoDuration(scene.video_url)
+ videoDuration = await getVideoDuration(scene.video_url);
} catch (error) {
- console.warn('Failed to get video duration, using default or scene duration:', error)
- videoDuration = scene.duration || 5
+ console.warn(
+ "Failed to get video duration, using default or scene duration:",
+ error,
+ );
+ videoDuration = scene.duration || 5;
}
}
// 计算新片段的位置
- let clipPosition: number
- let insertAfterIndex: number | null = null
-
+ let clipPosition: number;
+ let insertAfterIndex: number | null = null;
+
if (insertAtPosition !== undefined && timelineClips.value.length > 0) {
// 如果指定了插入位置,找到应该插入的位置
- clipPosition = insertAtPosition
+ clipPosition = insertAtPosition;
} else if (selectedClipId.value && timelineClips.value.length > 0) {
// 如果有选中的片段,插入到选中片段之后
- const selectedIndex = timelineClips.value.findIndex(c => c.id === selectedClipId.value)
+ const selectedIndex = timelineClips.value.findIndex(
+ (c) => c.id === selectedClipId.value,
+ );
if (selectedIndex !== -1) {
- const selectedClip = timelineClips.value[selectedIndex]
- clipPosition = selectedClip.position + selectedClip.duration
- insertAfterIndex = selectedIndex
+ const selectedClip = timelineClips.value[selectedIndex];
+ clipPosition = selectedClip.position + selectedClip.duration;
+ insertAfterIndex = selectedIndex;
} else {
// 选中的片段不存在,添加到末尾
- const lastClip = timelineClips.value[timelineClips.value.length - 1]
- clipPosition = lastClip.position + lastClip.duration
+ const lastClip = timelineClips.value[timelineClips.value.length - 1];
+ clipPosition = lastClip.position + lastClip.duration;
}
} else {
// 默认添加到末尾(紧密连接)
if (timelineClips.value.length === 0) {
- clipPosition = 0 // 第一个片段从0开始
+ clipPosition = 0; // 第一个片段从0开始
} else {
// 添加到最后一个片段的结尾
- const lastClip = timelineClips.value[timelineClips.value.length - 1]
- clipPosition = lastClip.position + lastClip.duration
+ const lastClip = timelineClips.value[timelineClips.value.length - 1];
+ clipPosition = lastClip.position + lastClip.duration;
}
}
-
+
const newClip: TimelineClip = {
id: `clip_${Date.now()}_${scene.id}`,
storyboard_id: scene.storyboard_id,
storyboard_number: scene.storyboard_number,
video_url: scene.video_url,
+ asset_id: scene.asset_id, // 保存素材库ID
start_time: 0,
end_time: videoDuration,
duration: videoDuration,
position: clipPosition,
order: timelineClips.value.length,
transition: {
- type: 'fade',
- duration: 1.0
- }
- }
-
+ type: "fade",
+ duration: 1.0,
+ },
+ };
+
// 如果是插入到中间,需要调整后续片段的位置
- if (insertAfterIndex !== null && insertAfterIndex < timelineClips.value.length - 1) {
- const newDuration = newClip.duration
+ if (
+ insertAfterIndex !== null &&
+ insertAfterIndex < timelineClips.value.length - 1
+ ) {
+ const newDuration = newClip.duration;
// 将后续所有片段向后移动
for (let i = insertAfterIndex + 1; i < timelineClips.value.length; i++) {
- timelineClips.value[i].position += newDuration
+ timelineClips.value[i].position += newDuration;
}
}
-
- timelineClips.value.push(newClip)
- timelineClips.value.sort((a, b) => a.position - b.position)
- updateClipOrders()
-
+
+ timelineClips.value.push(newClip);
+ timelineClips.value.sort((a, b) => a.position - b.position);
+ updateClipOrders();
+
// 选中新添加的片段
- selectedClipId.value = newClip.id
-
- const insertInfo = insertAfterIndex !== null ? '(已插入到选中片段后)' : ''
- ElMessage.success(`已添加到时间线${insertInfo}`)
-}
+ selectedClipId.value = newClip.id;
+
+ const insertInfo = insertAfterIndex !== null ? "(已插入到选中片段后)" : "";
+ ElMessage.success(`已添加到时间线${insertInfo}`);
+};
// 一键添加全部场景
const addAllScenesInOrder = async () => {
if (availableStoryboards.value.length === 0) {
- ElMessage.warning('没有可用的场景')
- return
+ ElMessage.warning("没有可用的场景");
+ return;
}
// 按场景编号排序
- const sortedScenes = [...availableStoryboards.value].sort((a, b) =>
- a.storyboard_number - b.storyboard_number
- )
+ const sortedScenes = [...availableStoryboards.value].sort(
+ (a, b) => a.storyboard_number - b.storyboard_number,
+ );
// 清空当前选中,让所有场景都添加到末尾
- selectedClipId.value = null
+ selectedClipId.value = null;
// 批量添加(顺序添加以确保正确的时长)
for (const scene of sortedScenes) {
- await addClipToTimeline(scene)
+ await addClipToTimeline(scene);
}
- ElMessage.success(`已批量添加 ${sortedScenes.length} 个场景到时间线`)
-}
+ ElMessage.success(`已批量添加 ${sortedScenes.length} 个场景到时间线`);
+};
// 删除素材
const deleteAsset = async (scene: any) => {
if (!scene.isAsset) {
- ElMessage.warning('只能删除素材库中的视频')
- return
+ ElMessage.warning("只能删除素材库中的视频");
+ return;
}
try {
// 直接调用API删除
- const { assetAPI } = await import('@/api/asset')
- await assetAPI.deleteAsset(scene.assetId)
-
- ElMessage.success('删除成功')
-
+ const { assetAPI } = await import("@/api/asset");
+ await assetAPI.deleteAsset(scene.asset_id);
+
+ ElMessage.success("删除成功");
+
// 通知父组件刷新素材列表
- emit('asset-deleted')
+ emit("asset-deleted");
} catch (error: any) {
- console.error('删除素材失败:', error)
- ElMessage.error(error.message || '删除失败')
+ console.error("删除素材失败:", error);
+ ElMessage.error(error.message || "删除失败");
}
-}
+};
// 转场相关方法
const getTransitionStyle = (clip: TimelineClip) => {
// 转场指示器显示在片段开始位置
return {
- left: 100 + clip.position * pixelsPerSecond.value - 15 + 'px'
- }
-}
+ left: 100 + clip.position * pixelsPerSecond.value - 15 + "px",
+ };
+};
const getTransitionLabel = (clip: TimelineClip) => {
- if (!clip.transition || clip.transition.type === 'none') {
- return '无'
+ if (!clip.transition || clip.transition.type === "none") {
+ return "无";
}
const labels: Record<string, string> = {
- 'fade': '淡入',
- 'fadeblack': '黑场',
- 'fadewhite': '白场',
- 'fadegrays': '灰场',
- 'slideleft': '左滑',
- 'slideright': '右滑',
- 'slideup': '上滑',
- 'slidedown': '下滑',
- 'wipeleft': '左擦',
- 'wiperight': '右擦',
- 'wipeup': '上擦',
- 'wipedown': '下擦',
- 'circleopen': '圆开',
- 'circleclose': '圆关',
- 'dissolve': '溶解',
- 'distance': '距离',
- 'horzopen': '水平开',
- 'horzclose': '水平关',
- 'vertopen': '垂直开',
- 'vertclose': '垂直关'
- }
- return labels[clip.transition.type] || '转场'
-}
+ fade: "淡入",
+ fadeblack: "黑场",
+ fadewhite: "白场",
+ fadegrays: "灰场",
+ slideleft: "左滑",
+ slideright: "右滑",
+ slideup: "上滑",
+ slidedown: "下滑",
+ wipeleft: "左擦",
+ wiperight: "右擦",
+ wipeup: "上擦",
+ wipedown: "下擦",
+ circleopen: "圆开",
+ circleclose: "圆关",
+ dissolve: "溶解",
+ distance: "距离",
+ horzopen: "水平开",
+ horzclose: "水平关",
+ vertopen: "垂直开",
+ vertclose: "垂直关",
+ };
+ return labels[clip.transition.type] || "转场";
+};
const openTransitionDialog = (clip: TimelineClip) => {
- console.log('🎬 打开转场设置对话框:', {
+ console.log("🎬 打开转场设置对话框:", {
clip_id: clip.id,
storyboard_id: clip.storyboard_id,
order: clip.order,
- current_transition: clip.transition
- })
- editingTransitionClipId.value = clip.id
+ current_transition: clip.transition,
+ });
+ editingTransitionClipId.value = clip.id;
editingTransition.value = {
- type: clip.transition?.type || 'fade',
- duration: clip.transition?.duration || 1.0
- }
- transitionDialogVisible.value = true
-}
+ type: clip.transition?.type || "fade",
+ duration: clip.transition?.duration || 1.0,
+ };
+ transitionDialogVisible.value = true;
+};
const applyTransition = () => {
- const clip = timelineClips.value.find(c => c.id === editingTransitionClipId.value)
+ const clip = timelineClips.value.find(
+ (c) => c.id === editingTransitionClipId.value,
+ );
if (clip) {
clip.transition = {
type: editingTransition.value.type,
- duration: editingTransition.value.duration
- }
- console.log('✅ 转场效果已设置:', {
+ duration: editingTransition.value.duration,
+ };
+ console.log("✅ 转场效果已设置:", {
clip_id: clip.id,
storyboard_id: clip.storyboard_id,
order: clip.order,
- transition: clip.transition
- })
- ElMessage.success('转场效果已设置')
+ transition: clip.transition,
+ });
+ ElMessage.success("转场效果已设置");
} else {
- console.error('❌ 未找到目标片段:', editingTransitionClipId.value)
+ console.error("❌ 未找到目标片段:", editingTransitionClipId.value);
}
- transitionDialogVisible.value = false
-}
+ transitionDialogVisible.value = false;
+};
// 选择和删除片段
const selectClip = (clip: TimelineClip) => {
- selectedClipId.value = clip.id
-}
+ selectedClipId.value = clip.id;
+};
const removeClip = (clip: TimelineClip) => {
- const index = timelineClips.value.findIndex(c => c.id === clip.id)
+ const index = timelineClips.value.findIndex((c) => c.id === clip.id);
if (index !== -1) {
- timelineClips.value.splice(index, 1)
- updateClipOrders()
-
+ timelineClips.value.splice(index, 1);
+ updateClipOrders();
+
// 同时移除关联的音频片段
- const audioIndex = audioClips.value.findIndex(a => a.source_clip_id === clip.id)
+ const audioIndex = audioClips.value.findIndex(
+ (a) => a.source_clip_id === clip.id,
+ );
if (audioIndex !== -1) {
- audioClips.value.splice(audioIndex, 1)
- updateAudioClipOrders()
+ audioClips.value.splice(audioIndex, 1);
+ updateAudioClipOrders();
}
}
-}
+};
const clearAllClips = () => {
- if (timelineClips.value.length === 0) return
-
- timelineClips.value = []
- audioClips.value = []
- selectedClipId.value = null
- selectedAudioClipId.value = null
- currentTime.value = 0
- ElMessage.success('已清空轨道')
-}
+ if (timelineClips.value.length === 0) return;
+
+ timelineClips.value = [];
+ audioClips.value = [];
+ selectedClipId.value = null;
+ selectedAudioClipId.value = null;
+ currentTime.value = 0;
+ ElMessage.success("已清空轨道");
+};
const updateClipOrders = () => {
timelineClips.value.forEach((clip, index) => {
- clip.order = index
- })
-}
+ clip.order = index;
+ });
+};
// 音频片段管理
const extractAllAudio = async () => {
if (timelineClips.value.length === 0) {
- ElMessage.warning('时间线上没有视频片段')
- return
+ ElMessage.warning("时间线上没有视频片段");
+ return;
}
const loadingMessage = ElMessage.info({
- message: '正在从视频中提取音频轨道,请稍候...',
- duration: 0
- })
-
+ message: "正在从视频中提取音频轨道,请稍候...",
+ duration: 0,
+ });
+
try {
// 清空现有音频
- audioClips.value = []
-
+ audioClips.value = [];
+
// 收集所有视频URL
- const videoUrls = timelineClips.value.map(clip => clip.video_url)
-
+ const videoUrls = timelineClips.value.map((clip) => clip.video_url);
+
// 调用后端API批量提取音频
- const { audioAPI } = await import('@/api/audio')
- const response = await audioAPI.batchExtractAudio(videoUrls)
-
+ const { audioAPI } = await import("@/api/audio");
+ const response = await audioAPI.batchExtractAudio(videoUrls);
+
if (!response.results || response.results.length === 0) {
- throw new Error('音频提取失败,未返回结果')
+ throw new Error("音频提取失败,未返回结果");
}
-
+
// 为每个视频片段创建对应的音频片段
timelineClips.value.forEach((clip, index) => {
- const extractedAudio = response.results[index]
+ const extractedAudio = response.results[index];
if (!extractedAudio) {
- console.warn(`视频片段 ${index} 未能提取音频`)
- return
+ console.warn(`视频片段 ${index} 未能提取音频`);
+ return;
}
-
+
// 验证音频时长
- const audioDuration = extractedAudio.duration
+ const audioDuration = extractedAudio.duration;
if (!audioDuration || audioDuration <= 0) {
- console.error(`音频片段 ${index} 时长无效:`, audioDuration)
- throw new Error(`音频片段 ${index + 1} 时长无效`)
+ console.error(`音频片段 ${index} 时长无效:`, audioDuration);
+ throw new Error(`音频片段 ${index + 1} 时长无效`);
}
-
+
console.log(`音频片段 ${index}:`, {
video_duration: clip.duration,
audio_duration: audioDuration,
video_position: clip.position,
video_url: clip.video_url,
- audio_url: extractedAudio.audio_url
- })
-
+ audio_url: extractedAudio.audio_url,
+ });
+
const audioClip: AudioClip = {
id: `audio_${Date.now()}_${index}`,
source_clip_id: clip.id,
@@ -1124,48 +1280,48 @@ const extractAllAudio = async () => {
duration: audioDuration, // 使用提取的音频时长
position: clip.position, // 和视频片段在时间轴上相同位置
order: index,
- volume: 1.0
- }
- audioClips.value.push(audioClip)
- })
-
- updateAudioClipOrders()
- loadingMessage.close()
- ElMessage.success(`已成功提取 ${audioClips.value.length} 个音频片段`)
+ volume: 1.0,
+ };
+ audioClips.value.push(audioClip);
+ });
+
+ updateAudioClipOrders();
+ loadingMessage.close();
+ ElMessage.success(`已成功提取 ${audioClips.value.length} 个音频片段`);
} catch (error: any) {
- console.error('提取音频失败:', error)
- loadingMessage.close()
- ElMessage.error(error.message || '音频提取失败,请重试')
+ console.error("提取音频失败:", error);
+ loadingMessage.close();
+ ElMessage.error(error.message || "音频提取失败,请重试");
// 清空部分提取的音频
- audioClips.value = []
+ audioClips.value = [];
}
-}
+};
const selectAudioClip = (audio: AudioClip) => {
- selectedAudioClipId.value = audio.id
+ selectedAudioClipId.value = audio.id;
// 取消选中视频片段
- selectedClipId.value = null
-}
+ selectedClipId.value = null;
+};
const removeAudioClip = (audio: AudioClip) => {
- const index = audioClips.value.findIndex(a => a.id === audio.id)
+ const index = audioClips.value.findIndex((a) => a.id === audio.id);
if (index !== -1) {
- audioClips.value.splice(index, 1)
- updateAudioClipOrders()
+ audioClips.value.splice(index, 1);
+ updateAudioClipOrders();
}
-}
+};
const updateAudioClipOrders = () => {
audioClips.value.forEach((clip, index) => {
- clip.order = index
- })
-}
+ clip.order = index;
+ });
+};
// 拖拽音频片段
const startDragAudioClip = (event: MouseEvent, audio: AudioClip) => {
- if (dragState.value.isResizing) return
-
- event.stopPropagation()
+ if (dragState.value.isResizing) return;
+
+ event.stopPropagation();
dragState.value = {
isDragging: true,
isResizing: false,
@@ -1173,43 +1329,47 @@ const startDragAudioClip = (event: MouseEvent, audio: AudioClip) => {
startX: event.clientX,
startPosition: audio.position,
startTime: 0,
- originalDuration: audio.duration
- }
-
- selectedAudioClipId.value = audio.id
- document.addEventListener('mousemove', handleDragAudioMove)
- document.addEventListener('mouseup', handleDragAudioEnd)
-}
+ originalDuration: audio.duration,
+ };
+
+ selectedAudioClipId.value = audio.id;
+ document.addEventListener("mousemove", handleDragAudioMove);
+ document.addEventListener("mouseup", handleDragAudioEnd);
+};
const handleDragAudioMove = (event: MouseEvent) => {
- if (!dragState.value.isDragging || !dragState.value.clipId) return
-
- const audio = audioClips.value.find(a => a.id === dragState.value.clipId)
- if (!audio) return
-
- const deltaX = event.clientX - dragState.value.startX
- const deltaTime = deltaX / pixelsPerSecond.value
- const newPosition = Math.max(0, dragState.value.startPosition + deltaTime)
-
- audio.position = newPosition
-}
+ if (!dragState.value.isDragging || !dragState.value.clipId) return;
+
+ const audio = audioClips.value.find((a) => a.id === dragState.value.clipId);
+ if (!audio) return;
+
+ const deltaX = event.clientX - dragState.value.startX;
+ const deltaTime = deltaX / pixelsPerSecond.value;
+ const newPosition = Math.max(0, dragState.value.startPosition + deltaTime);
+
+ audio.position = newPosition;
+};
const handleDragAudioEnd = () => {
- dragState.value.isDragging = false
- dragState.value.clipId = null
-
- document.removeEventListener('mousemove', handleDragAudioMove)
- document.removeEventListener('mouseup', handleDragAudioEnd)
-
+ dragState.value.isDragging = false;
+ dragState.value.clipId = null;
+
+ document.removeEventListener("mousemove", handleDragAudioMove);
+ document.removeEventListener("mouseup", handleDragAudioEnd);
+
// 重新排序
- audioClips.value.sort((a, b) => a.position - b.position)
- updateAudioClipOrders()
-}
+ audioClips.value.sort((a, b) => a.position - b.position);
+ updateAudioClipOrders();
+};
// 调整音频片段大小
-const startResizeAudioClip = (event: MouseEvent, audio: AudioClip, side: 'left' | 'right') => {
- event.stopPropagation()
-
+const startResizeAudioClip = (
+ event: MouseEvent,
+ audio: AudioClip,
+ side: "left" | "right",
+) => {
+ event.stopPropagation();
+
dragState.value = {
isDragging: false,
isResizing: true,
@@ -1218,57 +1378,63 @@ const startResizeAudioClip = (event: MouseEvent, audio: AudioClip, side: 'left'
startX: event.clientX,
startPosition: audio.position,
startTime: audio.start_time,
- originalDuration: audio.duration
- }
-
- selectedAudioClipId.value = audio.id
- document.addEventListener('mousemove', handleResizeAudioMove)
- document.addEventListener('mouseup', handleResizeAudioEnd)
-}
+ originalDuration: audio.duration,
+ };
+
+ selectedAudioClipId.value = audio.id;
+ document.addEventListener("mousemove", handleResizeAudioMove);
+ document.addEventListener("mouseup", handleResizeAudioEnd);
+};
const handleResizeAudioMove = (event: MouseEvent) => {
- if (!dragState.value.isResizing || !dragState.value.clipId) return
-
- const audio = audioClips.value.find(a => a.id === dragState.value.clipId)
- if (!audio) return
-
- const deltaX = event.clientX - dragState.value.startX
- const deltaTime = deltaX / pixelsPerSecond.value
-
- if (dragState.value.resizeSide === 'left') {
- const newStartTime = Math.max(0, dragState.value.startTime + deltaTime)
- const maxStartTime = dragState.value.startTime + dragState.value.originalDuration - 0.1
-
- audio.start_time = Math.min(newStartTime, maxStartTime)
- audio.position = dragState.value.startPosition + deltaTime
- audio.duration = dragState.value.originalDuration - (audio.start_time - dragState.value.startTime)
+ if (!dragState.value.isResizing || !dragState.value.clipId) return;
+
+ const audio = audioClips.value.find((a) => a.id === dragState.value.clipId);
+ if (!audio) return;
+
+ const deltaX = event.clientX - dragState.value.startX;
+ const deltaTime = deltaX / pixelsPerSecond.value;
+
+ if (dragState.value.resizeSide === "left") {
+ const newStartTime = Math.max(0, dragState.value.startTime + deltaTime);
+ const maxStartTime =
+ dragState.value.startTime + dragState.value.originalDuration - 0.1;
+
+ audio.start_time = Math.min(newStartTime, maxStartTime);
+ audio.position = dragState.value.startPosition + deltaTime;
+ audio.duration =
+ dragState.value.originalDuration -
+ (audio.start_time - dragState.value.startTime);
} else {
- const newDuration = Math.max(0.1, dragState.value.originalDuration + deltaTime)
- const maxDuration = (audio.end_time - audio.start_time)
-
- audio.duration = Math.min(newDuration, maxDuration)
- audio.end_time = audio.start_time + audio.duration
+ const newDuration = Math.max(
+ 0.1,
+ dragState.value.originalDuration + deltaTime,
+ );
+ const maxDuration = audio.end_time - audio.start_time;
+
+ audio.duration = Math.min(newDuration, maxDuration);
+ audio.end_time = audio.start_time + audio.duration;
}
-}
+};
const handleResizeAudioEnd = () => {
- dragState.value.isResizing = false
- dragState.value.clipId = null
-
- document.removeEventListener('mousemove', handleResizeAudioMove)
- document.removeEventListener('mouseup', handleResizeAudioEnd)
-}
+ dragState.value.isResizing = false;
+ dragState.value.clipId = null;
+
+ document.removeEventListener("mousemove", handleResizeAudioMove);
+ document.removeEventListener("mouseup", handleResizeAudioEnd);
+};
// 拖拽和调整片段
interface DragState {
- isDragging: boolean
- isResizing: boolean
- resizeSide?: 'left' | 'right'
- clipId: string | null
- startX: number
- startPosition: number
- startTime: number
- originalDuration: number
+ isDragging: boolean;
+ isResizing: boolean;
+ resizeSide?: "left" | "right";
+ clipId: string | null;
+ startX: number;
+ startPosition: number;
+ startTime: number;
+ originalDuration: number;
}
const dragState = ref<DragState>({
@@ -1278,14 +1444,14 @@ const dragState = ref<DragState>({
startX: 0,
startPosition: 0,
startTime: 0,
- originalDuration: 0
-})
+ originalDuration: 0,
+});
// 拖拽移动片段位置
const startDragClip = (event: MouseEvent, clip: TimelineClip) => {
- if (dragState.value.isResizing) return
-
- event.stopPropagation()
+ if (dragState.value.isResizing) return;
+
+ event.stopPropagation();
dragState.value = {
isDragging: true,
isResizing: false,
@@ -1293,35 +1459,35 @@ const startDragClip = (event: MouseEvent, clip: TimelineClip) => {
startX: event.clientX,
startPosition: clip.position,
startTime: 0,
- originalDuration: clip.duration
- }
-
- selectedClipId.value = clip.id
- document.addEventListener('mousemove', handleDragMove)
- document.addEventListener('mouseup', handleDragEnd)
-}
+ originalDuration: clip.duration,
+ };
+
+ selectedClipId.value = clip.id;
+ document.addEventListener("mousemove", handleDragMove);
+ document.addEventListener("mouseup", handleDragEnd);
+};
const handleDragMove = (event: MouseEvent) => {
- if (!dragState.value.clipId) return
-
- const clip = timelineClips.value.find(c => c.id === dragState.value.clipId)
- if (!clip) return
-
+ if (!dragState.value.clipId) return;
+
+ const clip = timelineClips.value.find((c) => c.id === dragState.value.clipId);
+ if (!clip) return;
+
if (dragState.value.isDragging) {
// 计算新位置
- const deltaX = event.clientX - dragState.value.startX
- const deltaTime = deltaX / pixelsPerSecond.value
- let newPosition = Math.max(0, dragState.value.startPosition + deltaTime)
-
+ const deltaX = event.clientX - dragState.value.startX;
+ const deltaTime = deltaX / pixelsPerSecond.value;
+ let newPosition = Math.max(0, dragState.value.startPosition + deltaTime);
+
// 吸附到其他片段边缘
- newPosition = snapToNearby(newPosition, clip.id, clip.duration)
-
- clip.position = newPosition
- updateClipOrders()
+ newPosition = snapToNearby(newPosition, clip.id, clip.duration);
+
+ clip.position = newPosition;
+ updateClipOrders();
} else if (dragState.value.isResizing) {
- handleResizeMove(event, clip)
+ handleResizeMove(event, clip);
}
-}
+};
const handleDragEnd = () => {
dragState.value = {
@@ -1331,31 +1497,35 @@ const handleDragEnd = () => {
startX: 0,
startPosition: 0,
startTime: 0,
- originalDuration: 0
- }
-
- document.removeEventListener('mousemove', handleDragMove)
- document.removeEventListener('mouseup', handleDragEnd)
-
+ originalDuration: 0,
+ };
+
+ document.removeEventListener("mousemove", handleDragMove);
+ document.removeEventListener("mouseup", handleDragEnd);
+
// 重新排序片段并紧密连接
- timelineClips.value.sort((a, b) => a.position - b.position)
- compactClips()
- updateClipOrders()
-}
+ timelineClips.value.sort((a, b) => a.position - b.position);
+ compactClips();
+ updateClipOrders();
+};
// 紧密排列所有片段(消除空隙)
const compactClips = () => {
- let currentPosition = 0
+ let currentPosition = 0;
for (const clip of timelineClips.value) {
- clip.position = currentPosition
- currentPosition += clip.duration
+ clip.position = currentPosition;
+ currentPosition += clip.duration;
}
-}
+};
// 调整片段时长
-const startResizeClip = (event: MouseEvent, clip: TimelineClip, side: 'left' | 'right') => {
- event.stopPropagation()
-
+const startResizeClip = (
+ event: MouseEvent,
+ clip: TimelineClip,
+ side: "left" | "right",
+) => {
+ event.stopPropagation();
+
dragState.value = {
isDragging: false,
isResizing: true,
@@ -1363,457 +1533,479 @@ const startResizeClip = (event: MouseEvent, clip: TimelineClip, side: 'left' | '
clipId: clip.id,
startX: event.clientX,
startPosition: clip.position,
- startTime: side === 'left' ? clip.start_time : clip.end_time,
- originalDuration: clip.duration
- }
-
- selectedClipId.value = clip.id
- document.addEventListener('mousemove', handleDragMove)
- document.addEventListener('mouseup', handleDragEnd)
-}
+ startTime: side === "left" ? clip.start_time : clip.end_time,
+ originalDuration: clip.duration,
+ };
+
+ selectedClipId.value = clip.id;
+ document.addEventListener("mousemove", handleDragMove);
+ document.addEventListener("mouseup", handleDragEnd);
+};
const handleResizeMove = (event: MouseEvent, clip: TimelineClip) => {
- const deltaX = event.clientX - dragState.value.startX
- const deltaTime = deltaX / pixelsPerSecond.value
-
- if (dragState.value.resizeSide === 'left') {
+ const deltaX = event.clientX - dragState.value.startX;
+ const deltaTime = deltaX / pixelsPerSecond.value;
+
+ if (dragState.value.resizeSide === "left") {
// 调整开始时间(不改变位置,只改变裁剪点)
- const newStartTime = Math.max(0, dragState.value.startTime + deltaTime)
- const maxStartTime = clip.end_time - 0.1 // 至少保留0.1秒
-
- clip.start_time = Math.min(newStartTime, maxStartTime)
- clip.duration = clip.end_time - clip.start_time
-
+ const newStartTime = Math.max(0, dragState.value.startTime + deltaTime);
+ const maxStartTime = clip.end_time - 0.1; // 至少保留0.1秒
+
+ clip.start_time = Math.min(newStartTime, maxStartTime);
+ clip.duration = clip.end_time - clip.start_time;
+
// 调整左边缘后需要重新紧密连接
- const clipIndex = timelineClips.value.findIndex(c => c.id === clip.id)
+ const clipIndex = timelineClips.value.findIndex((c) => c.id === clip.id);
if (clipIndex > 0) {
// 调整前面片段的结束位置
- compactClipsFromIndex(clipIndex)
+ compactClipsFromIndex(clipIndex);
}
} else {
// 调整结束时间
- const scene = props.scenes.find(s => s.id === clip.scene_id)
- const maxDuration = scene?.duration || 10
- const maxEndTime = clip.start_time + maxDuration
-
- const newEndTime = Math.max(clip.start_time + 0.1, dragState.value.startTime + deltaTime)
- clip.end_time = Math.min(newEndTime, maxEndTime)
- clip.duration = clip.end_time - clip.start_time
-
+ const scene = props.scenes.find((s) => s.id === clip.scene_id);
+ const maxDuration = scene?.duration || 10;
+ const maxEndTime = clip.start_time + maxDuration;
+
+ const newEndTime = Math.max(
+ clip.start_time + 0.1,
+ dragState.value.startTime + deltaTime,
+ );
+ clip.end_time = Math.min(newEndTime, maxEndTime);
+ clip.duration = clip.end_time - clip.start_time;
+
// 调整右边缘后需要重新紧密连接后续片段
- const clipIndex = timelineClips.value.findIndex(c => c.id === clip.id)
+ const clipIndex = timelineClips.value.findIndex((c) => c.id === clip.id);
if (clipIndex < timelineClips.value.length - 1) {
- compactClipsFromIndex(clipIndex + 1)
+ compactClipsFromIndex(clipIndex + 1);
}
}
-}
+};
// 从指定索引开始重新紧密排列片段
const compactClipsFromIndex = (startIndex: number) => {
- if (startIndex >= timelineClips.value.length) return
-
+ if (startIndex >= timelineClips.value.length) return;
+
for (let i = startIndex; i < timelineClips.value.length; i++) {
if (i === 0) {
- timelineClips.value[i].position = 0
+ timelineClips.value[i].position = 0;
} else {
- const prevClip = timelineClips.value[i - 1]
- timelineClips.value[i].position = prevClip.position + prevClip.duration
+ const prevClip = timelineClips.value[i - 1];
+ timelineClips.value[i].position = prevClip.position + prevClip.duration;
}
}
-}
+};
// 吸附到附近片段
-const snapToNearby = (position: number, clipId: string, duration: number): number => {
- const snapThreshold = 5 / pixelsPerSecond.value // 5像素的吸附范围
-
+const snapToNearby = (
+ position: number,
+ clipId: string,
+ duration: number,
+): number => {
+ const snapThreshold = 5 / pixelsPerSecond.value; // 5像素的吸附范围
+
for (const other of timelineClips.value) {
- if (other.id === clipId) continue
-
- const otherEnd = other.position + other.duration
-
+ if (other.id === clipId) continue;
+
+ const otherEnd = other.position + other.duration;
+
// 吸附到前一个片段的结尾
if (Math.abs(position - otherEnd) < snapThreshold) {
- return otherEnd
+ return otherEnd;
}
-
+
// 吸附到后一个片段的开头
if (Math.abs(position + duration - other.position) < snapThreshold) {
- return other.position - duration
+ return other.position - duration;
}
}
-
+
// 吸附到起点
if (position < snapThreshold) {
- return 0
+ return 0;
}
-
- return position
-}
+
+ return position;
+};
// 缩放控制
const zoomIn = () => {
- zoom.value = Math.min(zoom.value * 1.2, 3)
-}
+ zoom.value = Math.min(zoom.value * 1.2, 3);
+};
const zoomOut = () => {
- zoom.value = Math.max(zoom.value / 1.2, 0.3)
-}
+ zoom.value = Math.max(zoom.value / 1.2, 0.3);
+};
const zoomReset = () => {
- zoom.value = 1
-}
+ zoom.value = 1;
+};
// 时间线点击跳转
const clickTimeline = (event: MouseEvent) => {
- if (dragState.value.isDragging || dragState.value.isResizing) return
-
- const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()
- const clickX = event.clientX - rect.left - 100
- const newTime = Math.max(0, clickX / pixelsPerSecond.value)
- seekToTime(newTime)
-}
+ if (dragState.value.isDragging || dragState.value.isResizing) return;
+
+ const rect = (event.currentTarget as HTMLElement).getBoundingClientRect();
+ const clickX = event.clientX - rect.left - 100;
+ const newTime = Math.max(0, clickX / pixelsPerSecond.value);
+ seekToTime(newTime);
+};
const seekToTime = (time: number) => {
- currentTime.value = time
-
+ currentTime.value = time;
+
// 找到对应时间的视频片段并播放
- const clip = timelineClips.value.find(c =>
- time >= c.position && time < c.position + c.duration
- )
-
+ const clip = timelineClips.value.find(
+ (c) => time >= c.position && time < c.position + c.duration,
+ );
+
if (clip && previewPlayer.value) {
// 切换视频源(如果需要)
if (previewPlayer.value.src !== clip.video_url) {
- previewPlayer.value.src = clip.video_url
+ previewPlayer.value.src = clip.video_url;
}
-
+
// 跳转到片段内的对应时间
- const offsetInClip = time - clip.position
- previewPlayer.value.currentTime = clip.start_time + offsetInClip
-
+ const offsetInClip = time - clip.position;
+ previewPlayer.value.currentTime = clip.start_time + offsetInClip;
+
if (isPlaying.value) {
- previewPlayer.value.play()
+ previewPlayer.value.play();
}
}
-
+
// 同步音频播放器
if (audioClips.value.length > 0 && audioPlayer.value) {
- const audioClip = audioClips.value.find(a =>
- time >= a.position && time < a.position + a.duration
- )
-
+ const audioClip = audioClips.value.find(
+ (a) => time >= a.position && time < a.position + a.duration,
+ );
+
if (audioClip) {
// 切换音频源(如果需要)
if (audioPlayer.value.src !== audioClip.audio_url) {
- audioPlayer.value.src = audioClip.audio_url
+ audioPlayer.value.src = audioClip.audio_url;
}
-
+
// 跳转到音频片段内的对应时间
- const offsetInAudioClip = time - audioClip.position
- audioPlayer.value.currentTime = audioClip.start_time + offsetInAudioClip
-
+ const offsetInAudioClip = time - audioClip.position;
+ audioPlayer.value.currentTime = audioClip.start_time + offsetInAudioClip;
+
if (isPlaying.value) {
- audioPlayer.value.play().catch(err => {
- console.warn('音频播放失败:', err)
- })
+ audioPlayer.value.play().catch((err) => {
+ console.warn("音频播放失败:", err);
+ });
}
} else {
// 当前位置没有音频,暂停音频播放器
- audioPlayer.value.pause()
+ audioPlayer.value.pause();
}
}
-}
+};
// 播放控制
const playTimeline = () => {
if (timelineClips.value.length === 0) {
- ElMessage.warning('时间线中没有视频片段')
- return
+ ElMessage.warning("时间线中没有视频片段");
+ return;
}
-
- isPlaying.value = true
-
+
+ isPlaying.value = true;
+
// 找到当前时间对应的视频片段
- const clip = timelineClips.value.find(c =>
- currentTime.value >= c.position && currentTime.value < c.position + c.duration
- )
-
+ const clip = timelineClips.value.find(
+ (c) =>
+ currentTime.value >= c.position &&
+ currentTime.value < c.position + c.duration,
+ );
+
if (clip && previewPlayer.value) {
if (previewPlayer.value.src !== clip.video_url) {
- previewPlayer.value.src = clip.video_url
+ previewPlayer.value.src = clip.video_url;
}
- const offsetInClip = currentTime.value - clip.position
- previewPlayer.value.currentTime = clip.start_time + offsetInClip
- previewPlayer.value.play()
+ const offsetInClip = currentTime.value - clip.position;
+ previewPlayer.value.currentTime = clip.start_time + offsetInClip;
+ previewPlayer.value.play();
} else if (timelineClips.value[0]) {
// 如果当前时间超出范围,从头开始播放
- currentTime.value = 0
- seekToTime(0)
- previewPlayer.value?.play()
+ currentTime.value = 0;
+ seekToTime(0);
+ previewPlayer.value?.play();
}
-
+
// 同时播放音频(如果有)
if (audioClips.value.length > 0 && audioPlayer.value) {
- const audioClip = audioClips.value.find(a =>
- currentTime.value >= a.position && currentTime.value < a.position + a.duration
- )
-
+ const audioClip = audioClips.value.find(
+ (a) =>
+ currentTime.value >= a.position &&
+ currentTime.value < a.position + a.duration,
+ );
+
if (audioClip) {
if (audioPlayer.value.src !== audioClip.audio_url) {
- audioPlayer.value.src = audioClip.audio_url
+ audioPlayer.value.src = audioClip.audio_url;
}
- const offsetInAudioClip = currentTime.value - audioClip.position
- audioPlayer.value.currentTime = audioClip.start_time + offsetInAudioClip
- audioPlayer.value.play().catch(err => {
- console.warn('音频播放失败:', err)
- })
+ const offsetInAudioClip = currentTime.value - audioClip.position;
+ audioPlayer.value.currentTime = audioClip.start_time + offsetInAudioClip;
+ audioPlayer.value.play().catch((err) => {
+ console.warn("音频播放失败:", err);
+ });
}
}
-}
+};
const pauseTimeline = () => {
- isPlaying.value = false
+ isPlaying.value = false;
if (previewPlayer.value) {
- previewPlayer.value.pause()
+ previewPlayer.value.pause();
}
// 同时暂停音频
if (audioPlayer.value) {
- audioPlayer.value.pause()
+ audioPlayer.value.pause();
}
-}
+};
const togglePlay = () => {
if (isPlaying.value) {
- pauseTimeline()
+ pauseTimeline();
} else {
- playTimeline()
+ playTimeline();
}
-}
+};
// 键盘快捷键
const handleKeyPress = (event: KeyboardEvent) => {
// 如果在输入框中,不处理快捷键
- if ((event.target as HTMLElement).tagName === 'INPUT') return
-
+ if ((event.target as HTMLElement).tagName === "INPUT") return;
+
switch (event.code) {
- case 'Space':
- event.preventDefault()
+ case "Space":
+ event.preventDefault();
if (isPlaying.value) {
- pauseTimeline()
+ pauseTimeline();
} else {
- playTimeline()
+ playTimeline();
}
- break
- case 'Delete':
- case 'Backspace':
+ break;
+ case "Delete":
+ case "Backspace":
if (selectedClipId.value) {
- event.preventDefault()
- const clip = timelineClips.value.find(c => c.id === selectedClipId.value)
- if (clip) removeClip(clip)
+ event.preventDefault();
+ const clip = timelineClips.value.find(
+ (c) => c.id === selectedClipId.value,
+ );
+ if (clip) removeClip(clip);
}
- break
- case 'ArrowLeft':
- event.preventDefault()
- seekToTime(Math.max(0, currentTime.value - 1))
- break
- case 'ArrowRight':
- event.preventDefault()
- seekToTime(Math.min(totalDuration.value, currentTime.value + 1))
- break
- case 'Home':
- event.preventDefault()
- seekToTime(0)
- break
- case 'End':
- event.preventDefault()
- seekToTime(totalDuration.value)
- break
- }
-}
+ break;
+ case "ArrowLeft":
+ event.preventDefault();
+ seekToTime(Math.max(0, currentTime.value - 1));
+ break;
+ case "ArrowRight":
+ event.preventDefault();
+ seekToTime(Math.min(totalDuration.value, currentTime.value + 1));
+ break;
+ case "Home":
+ event.preventDefault();
+ seekToTime(0);
+ break;
+ case "End":
+ event.preventDefault();
+ seekToTime(totalDuration.value);
+ break;
+ }
+};
// 生命周期管理
onMounted(() => {
- document.addEventListener('keydown', handleKeyPress)
-})
+ document.addEventListener("keydown", handleKeyPress);
+});
onUnmounted(() => {
- document.removeEventListener('keydown', handleKeyPress)
- document.removeEventListener('mousemove', handleDragMove)
- document.removeEventListener('mouseup', handleDragEnd)
-})
+ document.removeEventListener("keydown", handleKeyPress);
+ document.removeEventListener("mousemove", handleDragMove);
+ document.removeEventListener("mouseup", handleDragEnd);
+});
// 进度显示辅助函数
const getPhaseType = (phase: string) => {
switch (phase) {
- case 'loading': return 'info'
- case 'processing': return 'warning'
- case 'encoding': return 'warning'
- case 'completed': return 'success'
- default: return 'info'
- }
-}
+ case "loading":
+ return "info";
+ case "processing":
+ return "warning";
+ case "encoding":
+ return "warning";
+ case "completed":
+ return "success";
+ default:
+ return "info";
+ }
+};
const getPhaseText = (phase: string) => {
switch (phase) {
- case 'loading': return '初始化'
- case 'processing': return '处理中'
- case 'encoding': return '编码中'
- case 'completed': return '完成'
- default: return '准备中'
- }
-}
+ case "loading":
+ return "初始化";
+ case "processing":
+ return "处理中";
+ case "encoding":
+ return "编码中";
+ case "completed":
+ return "完成";
+ default:
+ return "准备中";
+ }
+};
// 导出功能
const handleExport = async () => {
if (timelineClips.value.length === 0) {
- ElMessage.warning('请至少添加一个视频片段')
- return
+ ElMessage.warning("请至少添加一个视频片段");
+ return;
}
try {
// 计算总视频大小(粗略估算)
- const totalSize = timelineClips.value.length * 20 // 假设每个片段约20MB
- const estimatedTime = Math.ceil(totalSize / 50) // 每50MB约1分钟
-
+ const totalSize = timelineClips.value.length * 20; // 假设每个片段约20MB
+ const estimatedTime = Math.ceil(totalSize / 50); // 每50MB约1分钟
+
await ElMessageBox.confirm(
`即将在浏览器中合并 ${timelineClips.value.length} 个视频片段。\n\n` +
- `预计处理时间:${estimatedTime}-${estimatedTime + 1} 分钟\n` +
- `预计内存占用:约 ${Math.round(totalSize * 1.5)}MB\n\n` +
- `处理期间请勿关闭页面。`,
- '确认导出',
+ `预计处理时间:${estimatedTime}-${estimatedTime + 1} 分钟\n` +
+ `预计内存占用:约 ${Math.round(totalSize * 1.5)}MB\n\n` +
+ `处理期间请勿关闭页面。`,
+ "确认导出",
{
- confirmButtonText: '开始合并',
- cancelButtonText: '取消',
- type: 'warning',
- dangerouslyUseHTMLString: true
- }
- )
+ confirmButtonText: "开始合并",
+ cancelButtonText: "取消",
+ type: "warning",
+ dangerouslyUseHTMLString: true,
+ },
+ );
- mergeDialogVisible.value = true
- merging.value = true
+ mergeDialogVisible.value = true;
+ merging.value = true;
// 初始化FFmpeg
await videoMerger.initialize((progress) => {
- mergeProgress.value = progress
- })
+ mergeProgress.value = progress;
+ });
// 准备视频片段数据(包含转场信息)
- const clips = timelineClips.value.map(clip => ({
+ const clips = timelineClips.value.map((clip) => ({
url: clip.video_url,
startTime: clip.start_time,
endTime: clip.end_time,
duration: clip.end_time - clip.start_time,
- transition: clip.transition
- }))
+ transition: clip.transition,
+ }));
// 执行合并
- const mergedBlob = await videoMerger.mergeVideos(clips)
+ const mergedBlob = await videoMerger.mergeVideos(clips);
// 下载合并后的视频
- const url = URL.createObjectURL(mergedBlob)
- const a = document.createElement('a')
- a.href = url
- a.download = `merged_video_${Date.now()}.mp4`
- document.body.appendChild(a)
- a.click()
- document.body.removeChild(a)
- URL.revokeObjectURL(url)
-
- ElMessage.success('视频合并完成,已开始下载!')
- mergeDialogVisible.value = false
+ const url = URL.createObjectURL(mergedBlob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = `merged_video_${Date.now()}.mp4`;
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(url);
+
+ ElMessage.success("视频合并完成,已开始下载!");
+ mergeDialogVisible.value = false;
} catch (error: any) {
- if (error !== 'cancel') {
- console.error('视频合并失败:', error)
- ElMessage.error(error.message || '视频合并失败')
+ if (error !== "cancel") {
+ console.error("视频合并失败:", error);
+ ElMessage.error(error.message || "视频合并失败");
}
} finally {
- merging.value = false
+ merging.value = false;
}
-}
+};
// 提交时间线数据到后端进行合成
// 浏览器端FFmpeg合成
const mergeVideoInBrowser = async () => {
if (timelineClips.value.length === 0) {
- ElMessage.warning('时间线上没有视频片段')
- return
+ ElMessage.warning("时间线上没有视频片段");
+ return;
}
-
try {
await ElMessageBox.confirm(
- '将在浏览器中使用FFmpeg合成视频。\n注意:处理时间较长,且会占用浏览器资源,请勿关闭页面。\n适合少量视频场景(1-5个)。\n是否继续?',
- '浏览器合成视频',
+ "将在浏览器中使用FFmpeg合成视频。\n注意:处理时间较长,且会占用浏览器资源,请勿关闭页面。\n适合少量视频场景(1-5个)。\n是否继续?",
+ "浏览器合成视频",
{
- confirmButtonText: '确定',
- cancelButtonText: '取消',
- type: 'warning'
- }
- )
+ confirmButtonText: "确定",
+ cancelButtonText: "取消",
+ type: "warning",
+ },
+ );
- merging.value = true
- mergeProgress.value = 0
+ merging.value = true;
+ mergeProgress.value = 0;
- ElMessage.info('开始加载FFmpeg引擎...')
+ ElMessage.info("开始加载FFmpeg引擎...");
// 准备剪辑数据
- const clips = timelineClips.value.map(clip => ({
+ const clips = timelineClips.value.map((clip) => ({
url: clip.video_url,
startTime: clip.start_time,
- endTime: clip.end_time
- }))
+ endTime: clip.end_time,
+ }));
// 使用FFmpeg合成
- ElMessage.info('正在合成视频,请稍候...')
+ ElMessage.info("正在合成视频,请稍候...");
const mergedBlob = await trimAndMergeVideos(clips, (progress) => {
- mergeProgress.value = Math.round(progress)
- })
+ mergeProgress.value = Math.round(progress);
+ });
// 创建下载链接
- const url = URL.createObjectURL(mergedBlob)
- const link = document.createElement('a')
- link.href = url
- link.download = `episode_${props.episodeId}_merged.mp4`
- document.body.appendChild(link)
- link.click()
- document.body.removeChild(link)
- URL.revokeObjectURL(url)
-
- ElMessage.success('视频合成完成并已下载!')
- emit('merge-completed', 0)
+ const url = URL.createObjectURL(mergedBlob);
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = `episode_${props.episodeId}_merged.mp4`;
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ URL.revokeObjectURL(url);
+
+ ElMessage.success("视频合成完成并已下载!");
+ emit("merge-completed", 0);
} catch (error: any) {
- if (error !== 'cancel') {
+ if (error !== "cancel") {
ElMessage.error({
- message: `合成失败: ${error.message || '未知错误'}。请检查控制台或尝试服务器合成`,
- duration: 5000
- })
+ message: `合成失败: ${error.message || "未知错误"}。请检查控制台或尝试服务器合成`,
+ duration: 5000,
+ });
}
} finally {
- merging.value = false
- mergeProgress.value = 0
+ merging.value = false;
+ mergeProgress.value = 0;
}
-}
+};
// 服务器端合成
const submitTimelineForMerge = async () => {
if (timelineClips.value.length === 0) {
- ElMessage.warning('时间线上没有视频片段')
- return
+ ElMessage.warning("时间线上没有视频片段");
+ return;
}
try {
await ElMessageBox.confirm(
- '将根据时间线编排的顺序和转场效果合成最终视频。\n注意:未生成视频的场景将被跳过,只合成已有视频的场景。\n适合大量场景合成。\n是否继续?',
- '服务器合成视频',
+ "将根据时间线编排的顺序和转场效果合成最终视频。\n注意:未生成视频的场景将被跳过,只合成已有视频的场景。\n适合大量场景合成。\n是否继续?",
+ "服务器合成视频",
{
- confirmButtonText: '确定',
- cancelButtonText: '取消',
- type: 'warning',
- dangerouslyUseHTMLString: false
- }
- )
+ confirmButtonText: "确定",
+ cancelButtonText: "取消",
+ type: "warning",
+ dangerouslyUseHTMLString: false,
+ },
+ );
- serverMerging.value = true
+ serverMerging.value = true;
// 准备时间线数据
const timelineData = {
@@ -1821,77 +2013,92 @@ const submitTimelineForMerge = async () => {
clips: timelineClips.value.map((clip, index) => {
console.log(`📹 片段 ${index}:`, {
storyboard_id: clip.storyboard_id,
- transition: clip.transition
- })
+ asset_id: clip.asset_id,
+ transition: clip.transition,
+ });
return {
storyboard_id: String(clip.storyboard_id),
+ asset_id: clip.asset_id, // 包含素材库ID
order: index,
start_time: clip.start_time,
end_time: clip.end_time,
duration: clip.duration,
- transition: clip.transition || { type: 'none', duration: 0 }
- }
- })
- }
- console.log('📤 提交时间线数据:', JSON.stringify(timelineData, null, 2))
+ transition: clip.transition || { type: "none", duration: 0 },
+ };
+ }),
+ };
+ console.log("📤 提交时间线数据:", JSON.stringify(timelineData, null, 2));
// 调用后端API
- const { dramaAPI } = await import('@/api/drama')
- const result = await dramaAPI.finalizeEpisode(props.episodeId, timelineData)
-
+ const { dramaAPI } = await import("@/api/drama");
+ const result = await dramaAPI.finalizeEpisode(
+ props.episodeId,
+ timelineData,
+ );
+
// 如果有跳过的场景,显示警告
if (result.warning) {
ElMessage.warning({
message: result.warning,
- duration: 5000
- })
+ duration: 5000,
+ });
} else {
- ElMessage.success('视频合成任务已提交,正在后台处理...')
+ ElMessage.success("视频合成任务已提交,正在后台处理...");
}
-
- emit('merge-completed', result.merge_id || 0)
+
+ emit("merge-completed", result.merge_id || 0);
} catch (error: any) {
- if (error !== 'cancel') {
- console.error('提交合成任务失败:', error)
- ElMessage.error(error.response?.data?.message || '提交失败')
+ if (error !== "cancel") {
+ console.error("提交合成任务失败:", error);
+ ElMessage.error(error.response?.data?.message || "提交失败");
}
} finally {
- serverMerging.value = false
+ serverMerging.value = false;
}
-}
+};
// 暴露方法供父组件调用
-const updateClipsByStoryboardId = (storyboardId: string | number, newVideoUrl: string) => {
- console.log('=== updateClipsByStoryboardId 调用 ===')
- console.log('目标 storyboard_id:', storyboardId, '类型:', typeof storyboardId)
- console.log('新视频 URL:', newVideoUrl)
- console.log('当前时间线片段数量:', timelineClips.value.length)
-
- let updated = false
- const targetId = String(storyboardId) // 统一转换为字符串进行比较
-
+const updateClipsByStoryboardId = (
+ storyboardId: string | number,
+ newVideoUrl: string,
+) => {
+ console.log("=== updateClipsByStoryboardId 调用 ===");
+ console.log(
+ "目标 storyboard_id:",
+ storyboardId,
+ "类型:",
+ typeof storyboardId,
+ );
+ console.log("新视频 URL:", newVideoUrl);
+ console.log("当前时间线片段数量:", timelineClips.value.length);
+
+ let updated = false;
+ const targetId = String(storyboardId); // 统一转换为字符串进行比较
+
timelineClips.value.forEach((clip, index) => {
- console.log(`片段 ${index}: storyboard_id=${clip.storyboard_id} (类型: ${typeof clip.storyboard_id})`)
+ console.log(
+ `片段 ${index}: storyboard_id=${clip.storyboard_id} (类型: ${typeof clip.storyboard_id})`,
+ );
if (String(clip.storyboard_id) === targetId) {
- console.log(`✅ 匹配成功!更新片段 ${index} 的视频URL`)
- console.log(' 旧URL:', clip.video_url)
- console.log(' 新URL:', newVideoUrl)
- clip.video_url = newVideoUrl
- updated = true
+ console.log(`✅ 匹配成功!更新片段 ${index} 的视频URL`);
+ console.log(" 旧URL:", clip.video_url);
+ console.log(" 新URL:", newVideoUrl);
+ clip.video_url = newVideoUrl;
+ updated = true;
}
- })
-
+ });
+
if (updated) {
- console.log('✅ 时间线视频已更新')
- ElMessage.success('时间线中的视频已自动更新')
+ console.log("✅ 时间线视频已更新");
+ ElMessage.success("时间线中的视频已自动更新");
} else {
- console.log('⚠️ 没有找到匹配的时间线片段')
+ console.log("⚠️ 没有找到匹配的时间线片段");
}
-}
+};
defineExpose({
- updateClipsByStoryboardId
-})
+ updateClipsByStoryboardId,
+});
</script>
<style scoped lang="scss">
@@ -1916,7 +2123,7 @@ defineExpose({
gap: 16px;
.time-display {
- font-family: 'Courier New', monospace;
+ font-family: "Courier New", monospace;
font-size: 14px;
color: var(--text-secondary);
min-width: 160px;
@@ -1989,7 +2196,7 @@ defineExpose({
background: rgba(0, 0, 0, 0.4);
}
}
-
+
.transition-overlay {
position: absolute;
top: 0;
@@ -1999,7 +2206,7 @@ defineExpose({
pointer-events: none;
z-index: 10;
}
-
+
// 淡入淡出效果
.transition-fade.transition-out {
background: black;
@@ -2009,7 +2216,7 @@ defineExpose({
background: black;
animation: fadeIn forwards;
}
-
+
// 黑场过渡
.transition-fadeblack.transition-out {
background: black;
@@ -2019,7 +2226,7 @@ defineExpose({
background: black;
animation: fadeIn forwards;
}
-
+
// 白场过渡
.transition-fadewhite.transition-out {
background: white;
@@ -2029,7 +2236,7 @@ defineExpose({
background: white;
animation: fadeIn forwards;
}
-
+
// 左滑
.transition-slideleft.transition-out {
background: black;
@@ -2039,7 +2246,7 @@ defineExpose({
background: black;
animation: slideLeftIn forwards;
}
-
+
// 右滑
.transition-slideright.transition-out {
background: black;
@@ -2049,7 +2256,7 @@ defineExpose({
background: black;
animation: slideRightIn forwards;
}
-
+
// 上滑
.transition-slideup.transition-out {
background: black;
@@ -2059,7 +2266,7 @@ defineExpose({
background: black;
animation: slideUpIn forwards;
}
-
+
// 下滑
.transition-slidedown.transition-out {
background: black;
@@ -2069,55 +2276,95 @@ defineExpose({
background: black;
animation: slideDownIn forwards;
}
-
+
@keyframes fadeOut {
- from { opacity: 0; }
- to { opacity: 1; }
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
}
-
+
@keyframes fadeIn {
- from { opacity: 1; }
- to { opacity: 0; }
+ from {
+ opacity: 1;
+ }
+ to {
+ opacity: 0;
+ }
}
-
+
@keyframes slideLeftOut {
- from { transform: translateX(100%); }
- to { transform: translateX(0); }
+ from {
+ transform: translateX(100%);
+ }
+ to {
+ transform: translateX(0);
+ }
}
-
+
@keyframes slideLeftIn {
- from { transform: translateX(0); }
- to { transform: translateX(-100%); }
+ from {
+ transform: translateX(0);
+ }
+ to {
+ transform: translateX(-100%);
+ }
}
-
+
@keyframes slideRightOut {
- from { transform: translateX(-100%); }
- to { transform: translateX(0); }
+ from {
+ transform: translateX(-100%);
+ }
+ to {
+ transform: translateX(0);
+ }
}
-
+
@keyframes slideRightIn {
- from { transform: translateX(0); }
- to { transform: translateX(100%); }
+ from {
+ transform: translateX(0);
+ }
+ to {
+ transform: translateX(100%);
+ }
}
-
+
@keyframes slideUpOut {
- from { transform: translateY(100%); }
- to { transform: translateY(0); }
+ from {
+ transform: translateY(100%);
+ }
+ to {
+ transform: translateY(0);
+ }
}
-
+
@keyframes slideUpIn {
- from { transform: translateY(0); }
- to { transform: translateY(-100%); }
+ from {
+ transform: translateY(0);
+ }
+ to {
+ transform: translateY(-100%);
+ }
}
-
+
@keyframes slideDownOut {
- from { transform: translateY(-100%); }
- to { transform: translateY(0); }
+ from {
+ transform: translateY(-100%);
+ }
+ to {
+ transform: translateY(0);
+ }
}
-
+
@keyframes slideDownIn {
- from { transform: translateY(0); }
- to { transform: translateY(100%); }
+ from {
+ transform: translateY(0);
+ }
+ to {
+ transform: translateY(100%);
+ }
}
}
@@ -2184,7 +2431,7 @@ defineExpose({
&::-webkit-scrollbar-thumb {
background: var(--border-secondary);
border-radius: 4px;
-
+
&:hover {
background: var(--border-primary);
}
@@ -2202,7 +2449,7 @@ defineExpose({
&:hover {
border-color: var(--el-color-primary);
transform: translateY(-2px);
- box-shadow: 0 4px 12px rgba(0,0,0,0.1);
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.delete-btn {
@@ -2364,7 +2611,7 @@ defineExpose({
left: 4px;
font-size: 10px;
color: var(--text-muted);
- font-family: 'Courier New', monospace;
+ font-family: "Courier New", monospace;
}
}
}
@@ -2534,7 +2781,7 @@ defineExpose({
opacity: 1;
}
}
-
+
.transition-indicator {
position: absolute;
top: 50%;
@@ -2595,7 +2842,7 @@ defineExpose({
.el-button {
color: var(--text-muted);
-
+
&:hover {
color: var(--accent);
}
diff --git a/web/src/views/drama/ProfessionalEditor.vue b/web/src/views/drama/ProfessionalEditor.vue
index 21cc156..c0bb176 100644
--- a/web/src/views/drama/ProfessionalEditor.vue
+++ b/web/src/views/drama/ProfessionalEditor.vue
@@ -3927,8 +3927,11 @@ const downloadVideo = async (url: string, title: string) => {
duration: 0,
});
+ // 处理相对路径,添加 /static/ 前缀
+ const videoUrl = url.startsWith("http") ? url : `/static/${url}`;
+
// 使用fetch获取视频blob
- const response = await fetch(url);
+ const response = await fetch(videoUrl);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
@@ -3960,7 +3963,9 @@ const downloadVideo = async (url: string, title: string) => {
// 预览合成视频
const previewMergedVideo = (url: string) => {
- window.open(url, "_blank");
+ // 处理相对路径,添加 /static/ 前缀
+ const videoUrl = url.startsWith("http") ? url : `/static/${url}`;
+ window.open(videoUrl, "_blank");
};
// 删除视频合成记录