🎬 火宝短剧 - 基于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
feat: complete 9-step pipeline — voice, TTS, compose, merge
Connor7b76a9322b77
diff --git a/backend/src/agents/index.ts b/backend/src/agents/index.tsindex 296c5c8..3bd1255 100644--- a/backend/src/agents/index.ts+++ b/backend/src/agents/index.ts@@ -8,6 +8,7 @@ import { getTextConfig } from '../services/ai.js'import { createScriptTools } from './tools/script-tools.js'import { createExtractTools } from './tools/extract-tools.js'import { createStoryboardTools } from './tools/storyboard-tools.js'+import { createVoiceTools } from './tools/voice-tools.js'function getModel() {const config = getTextConfig()@@ -18,7 +19,7 @@ function getModel() {return provider.chat(config.model)}-export const validAgentTypes = ['script_rewriter', 'extractor', 'storyboard_breaker']+export const validAgentTypes = ['script_rewriter', 'extractor', 'storyboard_breaker', 'voice_assigner']/*** 创建 agent 实例(per-request,工具已注入 episodeId/dramaId)@@ -101,6 +102,25 @@ export function createAgent(type: string, episodeId: number, dramaId: number): A})}+ case 'voice_assigner': {+ const tools = createVoiceTools(episodeId, dramaId)+ return new Agent({+ id: 'voice_assigner',+ name: '角色音色分配',+ instructions: `你是配音导演,擅长为角色选择合适的音色。++工作流程:+1. 调用 list_voices 获取可用音色列表+2. 调用 get_characters 获取所有角色信息+3. 根据每个角色的性别、性格、年龄、角色定位,选择最匹配的音色+4. 对每个角色调用 assign_voice 分配音色,并说明选择理由++注意:每个角色都必须分配音色,不要遗漏。`,+ model,+ tools,+ })+ }+default:return null}diff --git a/backend/src/agents/tools/voice-tools.ts b/backend/src/agents/tools/voice-tools.tsnew file mode 100644index 0000000..52a286f--- /dev/null+++ b/backend/src/agents/tools/voice-tools.ts@@ -0,0 +1,66 @@+/**+ * 角色音色分配 Agent 工具+ */+import { createTool } from '@mastra/core/tools'+import { z } from 'zod'+import { db, schema } from '../../db/index.js'+import { eq } from 'drizzle-orm'+import { now } from '../../utils/response.js'++export function createVoiceTools(episodeId: number, dramaId: number) {+ const getCharacters = createTool({+ id: 'get_characters',+ description: 'Get all characters for the current drama with their current voice assignments.',+ inputSchema: z.object({}),+ execute: async () => {+ const chars = db.select().from(schema.characters)+ .where(eq(schema.characters.dramaId, dramaId)).all()+ return {+ characters: chars.map(c => ({+ id: c.id,+ name: c.name,+ role: c.role,+ personality: c.personality,+ description: c.description,+ current_voice: c.voiceStyle || '未分配',+ })),+ }+ },+ })++ const listVoices = createTool({+ id: 'list_voices',+ description: 'List all available voice options for TTS.',+ inputSchema: z.object({}),+ execute: async () => ({+ voices: [+ { id: 'alloy', gender: '中性', traits: '平衡自然', suitable_for: '旁白、通用' },+ { id: 'echo', gender: '男', traits: '低沉稳重', suitable_for: '成熟男性、旁白' },+ { id: 'fable', gender: '男', traits: '温暖富有表现力', suitable_for: '年轻男性、故事叙述' },+ { id: 'onyx', gender: '男', traits: '深沉有力', suitable_for: '权威角色、反派' },+ { id: 'nova', gender: '女', traits: '温柔甜美', suitable_for: '年轻女性、女主' },+ { id: 'shimmer', gender: '女', traits: '明亮活泼', suitable_for: '活泼女性、少女' },+ ],+ instruction: '根据角色的性别、性格、年龄来匹配最合适的音色。',+ }),+ })++ const assignVoice = createTool({+ id: 'assign_voice',+ description: 'Assign a voice to a character.',+ inputSchema: z.object({+ character_id: z.number().describe('Character ID'),+ voice_id: z.string().describe('Voice ID from list_voices'),+ reason: z.string().optional().describe('Why this voice fits'),+ }),+ execute: async ({ character_id, voice_id, reason }) => {+ db.update(schema.characters)+ .set({ voiceStyle: voice_id, voiceProvider: voice_id, updatedAt: now() })+ .where(eq(schema.characters.id, character_id))+ .run()+ return { message: `Assigned voice "${voice_id}" to character ${character_id}`, reason }+ },+ })++ return { getCharacters, listVoices, assignVoice }+}diff --git a/backend/src/db/schema.ts b/backend/src/db/schema.tsindex 9b28279..5ac6dc6 100644--- a/backend/src/db/schema.ts+++ b/backend/src/db/schema.ts@@ -52,6 +52,8 @@ export const characters = sqliteTable('characters', {seedValue: text('seed_value'),sortOrder: integer('sort_order'),localPath: text('local_path'),+ voiceSampleUrl: text('voice_sample_url'),+ voiceProvider: text('voice_provider'),createdAt: text('created_at').notNull(),updatedAt: text('updated_at').notNull(),deletedAt: text('deleted_at'),@@ -96,6 +98,9 @@ export const storyboards = sqliteTable('storyboards', {duration: integer('duration').default(0),composedImage: text('composed_image'),videoUrl: text('video_url'),+ ttsAudioUrl: text('tts_audio_url'),+ subtitleUrl: text('subtitle_url'),+ composedVideoUrl: text('composed_video_url'),status: text('status').default('pending'),createdAt: text('created_at').notNull(),updatedAt: text('updated_at').notNull(),diff --git a/backend/src/index.ts b/backend/src/index.tsindex caa6cec..0d6e434 100644--- a/backend/src/index.ts+++ b/backend/src/index.ts@@ -16,6 +16,8 @@ import upload from './routes/upload.js'import aiConfigs, { aiProviders } from './routes/aiConfigs.js'import agentConfigs from './routes/agentConfigs.js'import agent from './routes/agent.js'+import compose from './routes/compose.js'+import merge from './routes/merge.js'import { requestLogger, errorHandler } from './middleware/logger.js'const __dirname = path.dirname(fileURLToPath(import.meta.url))@@ -48,6 +50,8 @@ api.route('/ai-configs', aiConfigs)api.route('/ai-providers', aiProviders)api.route('/agent-configs', agentConfigs)api.route('/agent', agent)+api.route('/compose', compose)+api.route('/merge', merge)app.route('/api/v1', api)diff --git a/backend/src/routes/characters.ts b/backend/src/routes/characters.tsindex 4ae86c2..45e2416 100644--- a/backend/src/routes/characters.ts+++ b/backend/src/routes/characters.ts@@ -1,7 +1,8 @@import { Hono } from 'hono'import { eq } from 'drizzle-orm'import { db, schema } from '../db/index.js'-import { success, now } from '../utils/response.js'+import { success, badRequest, now } from '../utils/response.js'+import { generateVoiceSample } from '../services/tts-generation.js'const app = new Hono()@@ -26,6 +27,24 @@ app.delete('/:id', async (c) => {return success(c)})+// POST /characters/:id/generate-voice-sample — 生成角色音色试听+app.post('/:id/generate-voice-sample', async (c) => {+ const id = Number(c.req.param('id'))+ const [char] = db.select().from(schema.characters).where(eq(schema.characters.id, id)).all()+ if (!char) return badRequest(c, 'Character not found')+ if (!char.voiceStyle) return badRequest(c, '请先分配音色')++ try {+ const audioPath = await generateVoiceSample(char.name, char.voiceStyle)+ db.update(schema.characters)+ .set({ voiceSampleUrl: audioPath, updatedAt: now() })+ .where(eq(schema.characters.id, id)).run()+ return success(c, { voice_sample_url: audioPath })+ } catch (err: any) {+ return badRequest(c, `TTS 生成失败: ${err.message}`)+ }+})+// POST /characters/:id/generate-image (placeholder)app.post('/:id/generate-image', async (c) => {return success(c, { message: 'Image generation queued' })diff --git a/backend/src/routes/compose.ts b/backend/src/routes/compose.tsnew file mode 100644index 0000000..854281f--- /dev/null+++ b/backend/src/routes/compose.ts@@ -0,0 +1,54 @@+import { Hono } from 'hono'+import { eq } from 'drizzle-orm'+import { db, schema } from '../db/index.js'+import { success, badRequest } from '../utils/response.js'+import { composeStoryboard } from '../services/ffmpeg-compose.js'++const app = new Hono()++// POST /storyboards/:id/compose — 合成单个镜头+app.post('/storyboards/:id/compose', async (c) => {+ const id = Number(c.req.param('id'))+ try {+ const composedUrl = await composeStoryboard(id)+ return success(c, { id, composed_video_url: composedUrl })+ } catch (err: any) {+ return badRequest(c, err.message)+ }+})++// POST /episodes/:id/compose-all — 批量合成全部镜头+app.post('/episodes/:id/compose-all', async (c) => {+ const episodeId = Number(c.req.param('id'))+ const storyboards = db.select().from(schema.storyboards)+ .where(eq(schema.storyboards.episodeId, episodeId))+ .orderBy(schema.storyboards.storyboardNumber)+ .all()++ if (storyboards.length === 0) return badRequest(c, 'No storyboards found')++ const withVideo = storyboards.filter(sb => sb.videoUrl)+ if (withVideo.length === 0) return badRequest(c, 'No storyboards have video yet')++ // 异步处理+ const results: { id: number; status: string; url?: string; error?: string }[] = []++ // 立即返回,后台处理+ ;(async () => {+ for (const sb of withVideo) {+ try {+ await composeStoryboard(sb.id)+ } catch (err: any) {+ console.error(`[Compose] Failed storyboard ${sb.id}:`, err.message)+ }+ }+ console.log(`[Compose] All ${withVideo.length} storyboards composed for episode ${episodeId}`)+ })()++ return success(c, {+ message: `Started composing ${withVideo.length} storyboards`,+ total: withVideo.length,+ })+})++export default appdiff --git a/backend/src/routes/episodes.ts b/backend/src/routes/episodes.tsindex 0122665..853ee8d 100644--- a/backend/src/routes/episodes.ts+++ b/backend/src/routes/episodes.ts@@ -38,4 +38,45 @@ app.get('/:episode_id/storyboards', async (c) => {return success(c, rows)})+// GET /episodes/:id/pipeline-status — 流水线进度+app.get('/:id/pipeline-status', async (c) => {+ const episodeId = Number(c.req.param('id'))+ const [ep] = db.select().from(schema.episodes).where(eq(schema.episodes.id, episodeId)).all()+ if (!ep) return notFound(c, 'Episode not found')++ const chars = db.select().from(schema.characters).where(eq(schema.characters.dramaId, ep.dramaId)).all()+ const scenes = db.select().from(schema.scenes).where(eq(schema.scenes.dramaId, ep.dramaId)).all()+ const sbs = db.select().from(schema.storyboards).where(eq(schema.storyboards.episodeId, episodeId)).all()+ const merges = db.select().from(schema.videoMerges).where(eq(schema.videoMerges.episodeId, episodeId)).all()++ const charsWithVoice = chars.filter(c => c.voiceStyle)+ const charsWithSample = chars.filter(c => c.voiceSampleUrl)+ const sbsWithImage = sbs.filter(s => s.composedImage)+ const sbsWithVideo = sbs.filter(s => s.videoUrl)+ const sbsComposed = sbs.filter(s => s.composedVideoUrl)+ const latestMerge = merges[merges.length - 1]++ function stepStatus(done: boolean, partial?: boolean) {+ if (done) return 'done'+ if (partial) return 'partial'+ return 'pending'+ }++ return success(c, {+ episode_id: episodeId,+ steps: {+ script_rewrite: { status: ep.scriptContent ? 'done' : (ep.content ? 'ready' : 'pending') },+ extract_characters: { status: stepStatus(chars.length > 0), count: chars.length },+ extract_scenes: { status: stepStatus(scenes.length > 0), count: scenes.length },+ assign_voices: { status: stepStatus(charsWithVoice.length === chars.length && chars.length > 0, charsWithVoice.length > 0), assigned: charsWithVoice.length, total: chars.length },+ generate_voice_samples: { status: stepStatus(charsWithSample.length === charsWithVoice.length && charsWithVoice.length > 0, charsWithSample.length > 0), completed: charsWithSample.length, total: charsWithVoice.length },+ extract_storyboards: { status: stepStatus(sbs.length > 0), count: sbs.length },+ generate_images: { status: stepStatus(sbsWithImage.length === sbs.length && sbs.length > 0, sbsWithImage.length > 0), completed: sbsWithImage.length, total: sbs.length },+ generate_videos: { status: stepStatus(sbsWithVideo.length === sbs.length && sbs.length > 0, sbsWithVideo.length > 0), completed: sbsWithVideo.length, total: sbs.length },+ compose_shots: { status: stepStatus(sbsComposed.length === sbs.length && sbs.length > 0, sbsComposed.length > 0), completed: sbsComposed.length, total: sbs.length },+ merge_episode: { status: latestMerge?.status === 'completed' ? 'done' : (latestMerge ? latestMerge.status : 'pending'), merged_url: latestMerge?.mergedUrl },+ },+ })+})+export default appdiff --git a/backend/src/routes/merge.ts b/backend/src/routes/merge.tsnew file mode 100644index 0000000..c42aead--- /dev/null+++ b/backend/src/routes/merge.ts@@ -0,0 +1,37 @@+import { Hono } from 'hono'+import { eq } from 'drizzle-orm'+import { db, schema } from '../db/index.js'+import { success, badRequest } from '../utils/response.js'+import { mergeEpisodeVideos } from '../services/ffmpeg-merge.js'+import { toSnakeCase } from '../utils/transform.js'++const app = new Hono()++// POST /episodes/:id/merge — 拼接全集视频+app.post('/episodes/:id/merge', async (c) => {+ const episodeId = Number(c.req.param('id'))+ const [ep] = db.select().from(schema.episodes).where(eq(schema.episodes.id, episodeId)).all()+ if (!ep) return badRequest(c, 'Episode not found')++ try {+ const mergeId = await mergeEpisodeVideos(episodeId, ep.dramaId)+ return success(c, { merge_id: mergeId, status: 'processing' })+ } catch (err: any) {+ return badRequest(c, err.message)+ }+})++// GET /episodes/:id/merge — 查询拼接状态+app.get('/episodes/:id/merge', async (c) => {+ const episodeId = Number(c.req.param('id'))+ const merges = db.select().from(schema.videoMerges)+ .where(eq(schema.videoMerges.episodeId, episodeId))+ .all()++ const latest = merges[merges.length - 1]+ if (!latest) return success(c, null)++ return success(c, toSnakeCase(latest))+})++export default appdiff --git a/backend/src/services/ai.ts b/backend/src/services/ai.tsindex 18a6d29..ace82ce 100644--- a/backend/src/services/ai.ts+++ b/backend/src/services/ai.ts@@ -4,6 +4,8 @@import { db, schema } from '../db/index.js'import { eq } from 'drizzle-orm'+export type ServiceType = 'text' | 'image' | 'video' | 'audio'+export interface AIConfig {provider: stringbaseUrl: string@@ -11,10 +13,7 @@ export interface AIConfig {model: string}-/**- * 获取指定服务类型的活跃 AI 配置- */-export function getActiveConfig(serviceType: 'text' | 'image' | 'video'): AIConfig | null {+export function getActiveConfig(serviceType: ServiceType): AIConfig | null {const rows = db.select().from(schema.aiServiceConfigs).where(eq(schema.aiServiceConfigs.serviceType, serviceType)).all()@@ -31,20 +30,14 @@ export function getActiveConfig(serviceType: 'text' | 'image' | 'video'): AIConf}}-/**- * 构建 Mastra 模型标识符- * 格式:provider/model(如 openai/gpt-4o)- * 对于 chatfire 等中转服务,使用 openai compatible 模式- */-export function getModelId(serviceType: 'text' | 'image' | 'video' = 'text'): string {- const config = getActiveConfig(serviceType)- if (!config) throw new Error(`No active ${serviceType} AI config`)- // chatfire/openrouter 等中转站用 openai compatible 模式- return config.model-}-export function getTextConfig(): AIConfig {const config = getActiveConfig('text')if (!config) throw new Error('No active text AI config')return config}++export function getAudioConfig(): AIConfig {+ const config = getActiveConfig('audio')+ if (!config) throw new Error('No active audio AI config — 请在设置中添加音频服务')+ return config+}diff --git a/backend/src/services/ffmpeg-compose.ts b/backend/src/services/ffmpeg-compose.tsnew file mode 100644index 0000000..098002b--- /dev/null+++ b/backend/src/services/ffmpeg-compose.ts@@ -0,0 +1,132 @@+/**+ * FFmpeg 单镜头合成 — 视频 + TTS音频 + 烧录字幕+ */+import ffmpeg from 'fluent-ffmpeg'+import fs from 'fs'+import path from 'path'+import { fileURLToPath } from 'url'+import { v4 as uuid } from 'uuid'+import { db, schema } from '../db/index.js'+import { eq } from 'drizzle-orm'+import { now } from '../utils/response.js'+import { generateTTS } from './tts-generation.js'++const __dirname = path.dirname(fileURLToPath(import.meta.url))+const STORAGE_ROOT = process.env.STORAGE_PATH || path.resolve(__dirname, '../../../data/static')+const DATA_ROOT = path.resolve(__dirname, '../../../data')++function toAbsPath(relativePath: string): string {+ if (path.isAbsolute(relativePath)) return relativePath+ if (relativePath.startsWith('static/')) return path.join(DATA_ROOT, relativePath)+ return path.join(STORAGE_ROOT, relativePath)+}++/**+ * 合成单个镜头:视频 + TTS对白音频 + 烧录字幕+ */+export async function composeStoryboard(storyboardId: number): Promise<string> {+ const [sb] = db.select().from(schema.storyboards).where(eq(schema.storyboards.id, storyboardId)).all()+ if (!sb) throw new Error(`Storyboard ${storyboardId} not found`)+ if (!sb.videoUrl) throw new Error(`Storyboard ${storyboardId} has no video`)++ console.log(`[Compose] Start storyboard #${sb.storyboardNumber} (id=${storyboardId})`)++ const videoPath = toAbsPath(sb.videoUrl)+ let audioPath: string | null = null+ let subtitlePath: string | null = null++ // 1. 生成 TTS 音频(如果有对白)+ if (sb.dialogue && sb.dialogue.trim()) {+ // 查找角色的音色+ let voiceId = 'alloy' // 默认+ // 尝试从对白中提取角色名(格式:角色名:台词)+ const match = sb.dialogue.match(/^(.+?)[::]/)+ if (match) {+ const charName = match[1].replace(/[((].+?[))]/, '').trim()+ const chars = db.select().from(schema.characters)+ .where(eq(schema.characters.dramaId, sb.episodeId)).all() // 近似:通过 episode 找 drama+ // 从 episode 找 drama_id+ const [ep] = db.select().from(schema.episodes).where(eq(schema.episodes.id, sb.episodeId)).all()+ if (ep) {+ const allChars = db.select().from(schema.characters)+ .where(eq(schema.characters.dramaId, ep.dramaId)).all()+ const found = allChars.find(c => c.name === charName)+ if (found?.voiceStyle) voiceId = found.voiceStyle+ }+ }++ // 提取纯台词(去掉角色名前缀)+ const pureDialogue = sb.dialogue.replace(/^.+?[::]\s*/, '').replace(/[((].+?[))]/g, '').trim()+ if (pureDialogue) {+ const ttsPath = await generateTTS({ text: pureDialogue, voice: voiceId })+ audioPath = toAbsPath(ttsPath)+ db.update(schema.storyboards).set({ ttsAudioUrl: ttsPath, updatedAt: now() })+ .where(eq(schema.storyboards.id, storyboardId)).run()+ }+ }++ // 2. 生成字幕文件(SRT)+ if (sb.dialogue && sb.dialogue.trim()) {+ const srtDir = path.join(STORAGE_ROOT, 'subtitles')+ fs.mkdirSync(srtDir, { recursive: true })+ const srtFilename = `${uuid()}.srt`+ subtitlePath = path.join(srtDir, srtFilename)++ const duration = sb.duration || 10+ const pureText = sb.dialogue.replace(/^.+?[::]\s*/, '').replace(/[((].+?[))]/g, '').trim()+ const srtContent = `1\n00:00:00,500 --> 00:00:${String(Math.min(duration - 1, 59)).padStart(2, '0')},000\n${pureText}\n`+ fs.writeFileSync(subtitlePath, srtContent, 'utf-8')++ const srtRelative = `static/subtitles/${srtFilename}`+ db.update(schema.storyboards).set({ subtitleUrl: srtRelative, updatedAt: now() })+ .where(eq(schema.storyboards.id, storyboardId)).run()+ }++ // 3. FFmpeg 合成+ const outputDir = path.join(STORAGE_ROOT, 'composed')+ fs.mkdirSync(outputDir, { recursive: true })+ const outputFilename = `${uuid()}.mp4`+ const outputPath = path.join(outputDir, outputFilename)++ await new Promise<void>((resolve, reject) => {+ let cmd = ffmpeg(videoPath)++ if (audioPath) {+ cmd = cmd.input(audioPath)+ }++ const filters: string[] = []++ // 烧录字幕+ if (subtitlePath) {+ // 需要转义路径中的特殊字符+ const escapedPath = subtitlePath.replace(/\\/g, '/').replace(/:/g, '\\:')+ filters.push(`subtitles='${escapedPath}':force_style='FontSize=20,PrimaryColour=&HFFFFFF&,OutlineColour=&H000000&,Outline=2'`)+ }++ if (filters.length > 0) {+ cmd = cmd.videoFilter(filters)+ }++ const outputOptions = ['-c:v', 'libx264', '-preset', 'fast', '-crf', '23']++ if (audioPath) {+ outputOptions.push('-map', '0:v', '-map', '1:a', '-c:a', 'aac', '-shortest')+ } else {+ outputOptions.push('-an') // 无音频+ }++ cmd.outputOptions(outputOptions)+ .output(outputPath)+ .on('end', () => resolve())+ .on('error', (err) => reject(err))+ .run()+ })++ const composedRelative = `static/composed/${outputFilename}`+ db.update(schema.storyboards).set({ composedVideoUrl: composedRelative, updatedAt: now() })+ .where(eq(schema.storyboards.id, storyboardId)).run()++ console.log(`[Compose] Done storyboard #${sb.storyboardNumber} → ${composedRelative}`)+ return composedRelative+}diff --git a/backend/src/services/ffmpeg-merge.ts b/backend/src/services/ffmpeg-merge.tsnew file mode 100644index 0000000..839c611--- /dev/null+++ b/backend/src/services/ffmpeg-merge.ts@@ -0,0 +1,120 @@+/**+ * FFmpeg 多镜头拼接 — 将所有合成后的镜头视频拼接为一集+ */+import ffmpeg from 'fluent-ffmpeg'+import fs from 'fs'+import path from 'path'+import { fileURLToPath } from 'url'+import { v4 as uuid } from 'uuid'+import { db, schema } from '../db/index.js'+import { eq } from 'drizzle-orm'+import { now } from '../utils/response.js'++const __dirname = path.dirname(fileURLToPath(import.meta.url))+const STORAGE_ROOT = process.env.STORAGE_PATH || path.resolve(__dirname, '../../../data/static')+const DATA_ROOT = path.resolve(__dirname, '../../../data')++function toAbsPath(relativePath: string): string {+ if (path.isAbsolute(relativePath)) return relativePath+ if (relativePath.startsWith('static/')) return path.join(DATA_ROOT, relativePath)+ return path.join(STORAGE_ROOT, relativePath)+}++/**+ * 拼接一集的所有合成镜头视频+ */+export async function mergeEpisodeVideos(episodeId: number, dramaId: number): Promise<number> {+ const storyboards = db.select().from(schema.storyboards)+ .where(eq(schema.storyboards.episodeId, episodeId))+ .orderBy(schema.storyboards.storyboardNumber)+ .all()++ // 取有合成视频的镜头(composedVideoUrl),回退到原始视频(videoUrl)+ const videos = storyboards+ .map(sb => sb.composedVideoUrl || sb.videoUrl)+ .filter(Boolean) as string[]++ if (videos.length === 0) throw new Error('No videos to merge')++ console.log(`[Merge] Starting: ${videos.length} videos for episode ${episodeId}`)++ // 创建 merge 记录+ const ts = now()+ const res = db.insert(schema.videoMerges).values({+ episodeId,+ dramaId,+ title: `Episode ${episodeId} Merge`,+ status: 'processing',+ scenes: JSON.stringify(videos),+ createdAt: ts,+ }).run()+ const mergeId = Number(res.lastInsertRowid)++ // 异步执行+ doMerge(mergeId, episodeId, videos).catch(err => {+ console.error(`[Merge] Failed:`, err)+ db.update(schema.videoMerges)+ .set({ status: 'failed', errorMsg: err.message })+ .where(eq(schema.videoMerges.id, mergeId)).run()+ })++ return mergeId+}++async function doMerge(mergeId: number, episodeId: number, videos: string[]) {+ // 生成 concat 列表文件+ const listDir = path.join(STORAGE_ROOT, 'temp')+ fs.mkdirSync(listDir, { recursive: true })+ const listPath = path.join(listDir, `${uuid()}.txt`)++ const listContent = videos+ .map(v => `file '${toAbsPath(v)}'`)+ .join('\n')+ fs.writeFileSync(listPath, listContent, 'utf-8')++ // 输出文件+ const outputDir = path.join(STORAGE_ROOT, 'merged')+ fs.mkdirSync(outputDir, { recursive: true })+ const outputFilename = `${uuid()}.mp4`+ const outputPath = path.join(outputDir, outputFilename)++ await new Promise<void>((resolve, reject) => {+ ffmpeg()+ .input(listPath)+ .inputOptions(['-f', 'concat', '-safe', '0'])+ .outputOptions(['-c', 'copy'])+ .output(outputPath)+ .on('end', () => resolve())+ .on('error', (err) => reject(err))+ .run()+ })++ // 清理临时文件+ fs.unlinkSync(listPath)++ // 获取时长+ const duration = await getVideoDuration(outputPath)++ const mergedRelative = `static/merged/${outputFilename}`++ // 更新 merge 记录+ db.update(schema.videoMerges)+ .set({ status: 'completed', mergedUrl: mergedRelative, duration, completedAt: now() })+ .where(eq(schema.videoMerges.id, mergeId)).run()++ // 更新 episode+ db.update(schema.episodes)+ .set({ videoUrl: mergedRelative, updatedAt: now() })+ .where(eq(schema.episodes.id, episodeId)).run()++ console.log(`[Merge] Done: ${mergedRelative} (${duration}s, ${videos.length} clips)`)+}++function getVideoDuration(filePath: string): Promise<number> {+ return new Promise((resolve) => {+ ffmpeg.ffprobe(filePath, (err, metadata) => {+ if (err) { resolve(0); return }+ resolve(Math.round(metadata.format.duration || 0))+ })+ })+}diff --git a/backend/src/services/tts-generation.ts b/backend/src/services/tts-generation.tsnew file mode 100644index 0000000..833173d--- /dev/null+++ b/backend/src/services/tts-generation.ts@@ -0,0 +1,71 @@+/**+ * TTS 语音合成服务 — 调用 OpenAI 兼容 /audio/speech 接口+ */+import fs from 'fs'+import path from 'path'+import { fileURLToPath } from 'url'+import { v4 as uuid } from 'uuid'+import { getAudioConfig } from './ai.js'++const __dirname = path.dirname(fileURLToPath(import.meta.url))+const STORAGE_ROOT = process.env.STORAGE_PATH || path.resolve(__dirname, '../../../data/static')++interface TTSParams {+ text: string+ voice: string // 音色 ID,如 "alloy", "nova", "zh-CN-XiaoxiaoNeural"+ model?: string // TTS 模型,如 "tts-1", "tts-1-hd"+ speed?: number // 语速,0.25-4.0+}++/**+ * 生成 TTS 音频,返回本地文件路径+ */+export async function generateTTS(params: TTSParams): Promise<string> {+ const config = getAudioConfig()++ const body: Record<string, any> = {+ model: params.model || config.model || 'tts-1',+ input: params.text,+ voice: params.voice,+ response_format: 'mp3',+ }+ if (params.speed) body.speed = params.speed++ console.log(`[TTS] Generating: voice=${params.voice} text="${params.text.slice(0, 50)}..."`)++ const resp = await fetch(`${config.baseUrl}/audio/speech`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'Authorization': `Bearer ${config.apiKey}`,+ },+ body: JSON.stringify(body),+ })++ if (!resp.ok) {+ const errText = await resp.text()+ throw new Error(`TTS API error ${resp.status}: ${errText}`)+ }++ // 响应是二进制音频数据+ const buffer = Buffer.from(await resp.arrayBuffer())++ // 保存到本地+ const audioDir = path.join(STORAGE_ROOT, 'audio')+ fs.mkdirSync(audioDir, { recursive: true })+ const filename = `${uuid()}.mp3`+ const filePath = path.join(audioDir, filename)+ fs.writeFileSync(filePath, buffer)++ const relativePath = `static/audio/${filename}`+ console.log(`[TTS] Saved: ${relativePath} (${buffer.length} bytes)`)+ return relativePath+}++/**+ * 为角色生成试听音频+ */+export async function generateVoiceSample(characterName: string, voiceId: string): Promise<string> {+ const sampleText = `你好,我是${characterName}。很高兴认识你,这是我的声音试听。`+ return generateTTS({ text: sampleText, voice: voiceId })+}