Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e31cea40fd | |||
| 48ab2a4329 | |||
| 053291aa1c | |||
| a6ebb762e6 | |||
| c01062ab8a | |||
| 5c6ce75237 | |||
| ea9b5c8ab3 | |||
| 24efcdf038 | |||
| 42db72a8a4 |
Regular → Executable
+88
-281
@@ -1,47 +1,39 @@
|
||||
/**
|
||||
* 配音库页面 — V21 设计系统
|
||||
*
|
||||
* Phase 3: 逻辑抽离为 Hooks
|
||||
* - useVoicesData: 三 Tab 数据查询 + 筛选
|
||||
* - useAudioPlayer: 播放控制
|
||||
* - useCloneOperations: 克隆音色删除/重试/详情
|
||||
* - useTtsSynthesize: AI 配音合成
|
||||
* - useVoiceUpload: 上传音频
|
||||
* 主组件仅保留 Hook 组装与整体布局
|
||||
* 数据查询 → hooks/useVoicesData
|
||||
* 播放控制 → hooks/useAudioPlayer
|
||||
* 克隆操作 → hooks/useCloneOperations
|
||||
* TTS 合成 → hooks/useTtsSynthesize
|
||||
* 上传音频 → hooks/useVoiceUpload
|
||||
* Tab 切换 → components/VoiceTabBar
|
||||
* 预置音色 → components/PresetVoiceTab
|
||||
* 克隆音色 → components/ClonedVoiceTab
|
||||
* 配音素材 → components/MaterialVoiceTab
|
||||
* 弹窗集合 → components/VoiceModals
|
||||
* Toast 提示 → components/VoiceToasts
|
||||
*/
|
||||
import React, { useCallback, useState } from "react"
|
||||
import {
|
||||
SoundOutlined,
|
||||
PlusOutlined,
|
||||
RobotOutlined,
|
||||
UploadOutlined,
|
||||
AudioOutlined,
|
||||
UserOutlined,
|
||||
} from "@ant-design/icons"
|
||||
import { UploadOutlined, AudioOutlined, RobotOutlined } from "@ant-design/icons"
|
||||
import { Button } from "@/components/ui"
|
||||
import PageHead from "@/components/layout/PageHead"
|
||||
import { type AssetItem } from "@/api/assets"
|
||||
import { genderLabel, languageLabel } from "@/pages/voices/utils/format"
|
||||
import CloneModal from "@/components/voice/CloneModal"
|
||||
import VoiceCard from "@/pages/voices/components/VoiceCard"
|
||||
import CloneVoiceCard from "@/pages/voices/components/CloneVoiceCard"
|
||||
import CloneDetailModal from "@/pages/voices/components/CloneDetailModal"
|
||||
import CloneCardSkeleton from "@/pages/voices/components/CloneCardSkeleton"
|
||||
import UploadVoiceModal from "@/pages/voices/components/UploadVoiceModal"
|
||||
import TtsModal from "@/pages/voices/components/TtsModal"
|
||||
import VoiceFilterBar from "@/pages/voices/components/VoiceFilterBar"
|
||||
import { useVoicesData } from "@/pages/voices/hooks/useVoicesData"
|
||||
import { useAudioPlayer } from "@/pages/voices/hooks/useAudioPlayer"
|
||||
import { useCloneOperations } from "@/pages/voices/hooks/useCloneOperations"
|
||||
import { useTtsSynthesize } from "@/pages/voices/hooks/useTtsSynthesize"
|
||||
import { useVoiceUpload } from "@/pages/voices/hooks/useVoiceUpload"
|
||||
import VoiceTabBar from "./components/VoiceTabBar"
|
||||
import type { VoiceTabKey } from "./components/VoiceTabBar"
|
||||
import PresetVoiceTab from "./components/PresetVoiceTab"
|
||||
import ClonedVoiceTab from "./components/ClonedVoiceTab"
|
||||
import MaterialVoiceTab from "./components/MaterialVoiceTab"
|
||||
import VoiceModals from "./components/VoiceModals"
|
||||
import VoiceToasts from "./components/VoiceToasts"
|
||||
import type { Toast } from "./components/VoiceToasts"
|
||||
import { useVoicesData } from "./hooks/useVoicesData"
|
||||
import { useAudioPlayer } from "./hooks/useAudioPlayer"
|
||||
import { useCloneOperations } from "./hooks/useCloneOperations"
|
||||
import { useTtsSynthesize } from "./hooks/useTtsSynthesize"
|
||||
import { useVoiceUpload } from "./hooks/useVoiceUpload"
|
||||
import "./voices.css"
|
||||
|
||||
interface Toast {
|
||||
id: number
|
||||
message: string
|
||||
type: "success" | "error"
|
||||
}
|
||||
|
||||
let toastIdSeq = 0
|
||||
|
||||
const VoiceLibrary: React.FC = () => {
|
||||
@@ -138,17 +130,9 @@ const VoiceLibrary: React.FC = () => {
|
||||
handleUploadClose,
|
||||
} = useVoiceUpload({ showToast })
|
||||
|
||||
// ── 克隆音色播放切换 ──────────────────────────────────
|
||||
const handleClonePlayPause = useCallback(
|
||||
(voiceId: string, duration: number) => {
|
||||
handleTogglePlay(voiceId, duration)
|
||||
},
|
||||
[handleTogglePlay],
|
||||
)
|
||||
|
||||
// ── 切换 Tab 时停止播放 ───────────────────────────────
|
||||
const handleTabChange = useCallback(
|
||||
(tab: typeof activeTab) => {
|
||||
(tab: VoiceTabKey) => {
|
||||
setActiveTab(tab)
|
||||
stopPlayback()
|
||||
},
|
||||
@@ -200,254 +184,85 @@ const VoiceLibrary: React.FC = () => {
|
||||
actions={pageActions}
|
||||
/>
|
||||
|
||||
{/* ── Tabs ──────────────────────────────────────── */}
|
||||
<div className="xx-voices-tabs">
|
||||
<button
|
||||
className={`xx-voices-tab${activeTab === "preset" ? " active" : ""}`}
|
||||
onClick={() => handleTabChange("preset")}
|
||||
>
|
||||
<AudioOutlined />
|
||||
预置音色
|
||||
<span className="xx-voices-tab-count">{presetCount}</span>
|
||||
</button>
|
||||
<button
|
||||
className={`xx-voices-tab${activeTab === "cloned" ? " active" : ""}`}
|
||||
onClick={() => handleTabChange("cloned")}
|
||||
>
|
||||
<UserOutlined />
|
||||
我的克隆
|
||||
<span className="xx-voices-tab-count">{cloneCount}</span>
|
||||
</button>
|
||||
<button
|
||||
className={`xx-voices-tab${activeTab === "material" ? " active" : ""}`}
|
||||
onClick={() => handleTabChange("material")}
|
||||
>
|
||||
<SoundOutlined />
|
||||
配音素材
|
||||
<span className="xx-voices-tab-count">{materialCount}</span>
|
||||
</button>
|
||||
</div>
|
||||
{/* ── Tab 切换栏 ────────────────────────────────── */}
|
||||
<VoiceTabBar
|
||||
activeTab={activeTab as VoiceTabKey}
|
||||
presetCount={presetCount}
|
||||
cloneCount={cloneCount}
|
||||
materialCount={materialCount}
|
||||
onTabChange={handleTabChange}
|
||||
/>
|
||||
|
||||
{/* ── 预置音色 ──────────────────────────────────── */}
|
||||
{activeTab === "preset" && (
|
||||
<div className="xx-voices-tab-content">
|
||||
<VoiceFilterBar
|
||||
searchText={searchText}
|
||||
filterGender={filterGender}
|
||||
filterLang={filterLang}
|
||||
onSearchChange={setSearchText}
|
||||
onGenderChange={setFilterGender}
|
||||
onLangChange={setFilterLang}
|
||||
/>
|
||||
|
||||
{presetLoading && (
|
||||
<div className="xx-voices-empty">
|
||||
<div className="xx-voices-empty-icon">
|
||||
<SoundOutlined />
|
||||
</div>
|
||||
<p>加载预置音色中...</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!presetLoading && filteredPreset.length > 0 && (
|
||||
<div className="xx-voice-grid">
|
||||
{filteredPreset.map((voice) => (
|
||||
<VoiceCard
|
||||
key={voice.id}
|
||||
id={voice.id}
|
||||
name={voice.name}
|
||||
subtitle={`${genderLabel(voice.gender)} · ${languageLabel(voice.language)} · ${voice.description}`}
|
||||
tags={voice.tags}
|
||||
duration={voice.duration}
|
||||
gender={voice.gender}
|
||||
isPlaying={playingId === voice.id}
|
||||
isSelected={false}
|
||||
currentTime={playingId === voice.id ? currentTime : 0}
|
||||
starred={voice.starred}
|
||||
onPlay={() => handlePlay(voice.id, voice.duration)}
|
||||
onPause={handlePause}
|
||||
onSeek={(time) => handleSeek(voice.id, time, voice.duration)}
|
||||
onToggleStar={() => {}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!presetLoading && filteredPreset.length === 0 && (
|
||||
<div className="xx-voices-empty">
|
||||
<div className="xx-voices-empty-icon">
|
||||
<SoundOutlined />
|
||||
</div>
|
||||
<p>未找到匹配的音色</p>
|
||||
<Button buttonType="ghost" buttonSize="sm" onClick={handleClearFilters}>
|
||||
清除筛选条件
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<PresetVoiceTab
|
||||
searchText={searchText}
|
||||
filterGender={filterGender}
|
||||
filterLang={filterLang}
|
||||
onSearchChange={setSearchText}
|
||||
onGenderChange={setFilterGender}
|
||||
onLangChange={setFilterLang}
|
||||
loading={presetLoading}
|
||||
voices={filteredPreset}
|
||||
playingId={playingId}
|
||||
currentTime={currentTime}
|
||||
onPlay={handlePlay}
|
||||
onPause={handlePause}
|
||||
onSeek={handleSeek}
|
||||
onClearFilters={handleClearFilters}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* ── 我的克隆 ──────────────────────────────────── */}
|
||||
{activeTab === "cloned" && (
|
||||
<div className="xx-voices-tab-content">
|
||||
{/* 骨架屏加载 */}
|
||||
{cloneLoading && (
|
||||
<div className="xx-voice-grid">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<CloneCardSkeleton key={i} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 卡片列表 */}
|
||||
{!cloneLoading && clonedVoices.length > 0 && (
|
||||
<div className="xx-voice-grid">
|
||||
{clonedVoices.map((voice) => (
|
||||
<CloneVoiceCard
|
||||
key={voice.id}
|
||||
voice={voice}
|
||||
isPlaying={playingId === voice.id}
|
||||
currentTime={playingId === voice.id ? currentTime : 0}
|
||||
onPlay={() => handleClonePlayPause(voice.id, voice.duration)}
|
||||
onPause={handlePause}
|
||||
onUse={() => handleCloneUse(voice)}
|
||||
onDelete={() => handleCloneDelete(voice)}
|
||||
onRetry={() => handleCloneRetry(voice)}
|
||||
onShowDetail={() => handleShowDetail(voice)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 空状态 */}
|
||||
{!cloneLoading && clonedVoices.length === 0 && (
|
||||
<div className="xx-voices-empty">
|
||||
<div className="xx-voices-empty-icon">
|
||||
<UserOutlined />
|
||||
</div>
|
||||
<h3>暂无克隆音色</h3>
|
||||
<p>上传音频素材即可克隆专属音色</p>
|
||||
<Button buttonType="primary" buttonSize="md" onClick={() => setCloneModalOpen(true)}>
|
||||
<PlusOutlined /> 去克隆音色
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 处理中提示 */}
|
||||
{!cloneLoading && clonedVoices.some((v) => v.status === "processing") && (
|
||||
<div className="xx-clone-processing-hint">
|
||||
<RobotOutlined />
|
||||
<span>部分音色正在克隆处理中,完成后将自动出现在列表中。</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<ClonedVoiceTab
|
||||
loading={cloneLoading}
|
||||
voices={clonedVoices}
|
||||
playingId={playingId}
|
||||
currentTime={currentTime}
|
||||
onPlay={handleTogglePlay}
|
||||
onPause={handlePause}
|
||||
onUse={handleCloneUse}
|
||||
onDelete={handleCloneDelete}
|
||||
onRetry={handleCloneRetry}
|
||||
onShowDetail={handleShowDetail}
|
||||
onOpenClone={() => setCloneModalOpen(true)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* ── 配音素材 ──────────────────────────────────── */}
|
||||
{activeTab === "material" && (
|
||||
<div className="xx-voices-tab-content">
|
||||
{/* 骨架屏加载 */}
|
||||
{materialLoading && (
|
||||
<div className="xx-voice-grid">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<div key={i} className="vmat-card vmat-card--skeleton">
|
||||
<div className="vmat-thumb" />
|
||||
<div className="vmat-info">
|
||||
<div className="vmat-skeleton-line vmat-skeleton-title" />
|
||||
<div className="vmat-skeleton-line" />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 卡片列表 */}
|
||||
{!materialLoading && materials.length > 0 && (
|
||||
<div className="xx-voice-grid">
|
||||
{materials.map((asset: AssetItem) => {
|
||||
const duration = (asset.metadata?.duration as number) || 0
|
||||
const minutes = Math.floor(duration / 60)
|
||||
const seconds = Math.floor(duration % 60)
|
||||
return (
|
||||
<div key={asset.id} className="vmat-card">
|
||||
<div className="vmat-thumb">
|
||||
<AudioOutlined className="vmat-thumb-icon" />
|
||||
<span className="vmat-duration">
|
||||
{minutes}:{seconds.toString().padStart(2, "0")}
|
||||
</span>
|
||||
</div>
|
||||
<div className="vmat-info">
|
||||
<div className="vmat-name" title={asset.name}>
|
||||
{asset.name}
|
||||
</div>
|
||||
<div className="vmat-meta">
|
||||
<span>
|
||||
{asset.file_size
|
||||
? `${(asset.file_size / 1024 / 1024).toFixed(1)} MB`
|
||||
: "--"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 空状态 */}
|
||||
{!materialLoading && materials.length === 0 && (
|
||||
<div className="xx-voices-empty">
|
||||
<div className="xx-voices-empty-icon">
|
||||
<SoundOutlined />
|
||||
</div>
|
||||
<h3>暂无配音素材</h3>
|
||||
<p>上传您的音频素材,用于视频配音</p>
|
||||
<Button buttonType="primary" buttonSize="md" onClick={() => setUploadOpen(true)}>
|
||||
<UploadOutlined /> 上传音频
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── 克隆音色弹窗 ──────────────────────────────── */}
|
||||
<CloneModal
|
||||
open={cloneModalOpen}
|
||||
onClose={() => setCloneModalOpen(false)}
|
||||
onSuccess={handleCloneSuccess}
|
||||
/>
|
||||
|
||||
{/* ── 详情弹窗 ──────────────────────────────────── */}
|
||||
{detailVoice && (
|
||||
<CloneDetailModal
|
||||
voice={detailVoice}
|
||||
onClose={handleCloseDetail}
|
||||
onDelete={() => handleCloneDelete(detailVoice)}
|
||||
onRetry={() => handleCloneRetry(detailVoice)}
|
||||
onUse={() => handleCloneUse(detailVoice)}
|
||||
<MaterialVoiceTab
|
||||
loading={materialLoading}
|
||||
materials={materials as AssetItem[]}
|
||||
onOpenUpload={() => setUploadOpen(true)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* ── 上传音频弹窗 ──────────────────────────────── */}
|
||||
<UploadVoiceModal
|
||||
open={uploadOpen}
|
||||
{/* ── 弹窗集合 ──────────────────────────────────── */}
|
||||
<VoiceModals
|
||||
cloneModalOpen={cloneModalOpen}
|
||||
onCloneClose={() => setCloneModalOpen(false)}
|
||||
onCloneSuccess={handleCloneSuccess}
|
||||
detailVoice={detailVoice}
|
||||
onDetailClose={handleCloseDetail}
|
||||
onDetailDelete={() => detailVoice && handleCloneDelete(detailVoice)}
|
||||
onDetailRetry={() => detailVoice && handleCloneRetry(detailVoice)}
|
||||
onDetailUse={() => detailVoice && handleCloneUse(detailVoice)}
|
||||
uploadOpen={uploadOpen}
|
||||
uploadFile={uploadFile}
|
||||
uploadName={uploadName}
|
||||
uploadGender={uploadGender}
|
||||
uploadDesc={uploadDesc}
|
||||
uploadProgress={uploadProgress}
|
||||
onClose={handleUploadClose}
|
||||
onUploadClose={handleUploadClose}
|
||||
onFileSelect={handleFileSelect}
|
||||
onFileRemove={handleFileRemove}
|
||||
onNameChange={setUploadName}
|
||||
onGenderChange={setUploadGender}
|
||||
onDescChange={setUploadDesc}
|
||||
onUpload={handleUpload}
|
||||
/>
|
||||
|
||||
{/* ── AI 配音弹窗 ───────────────────────────────── */}
|
||||
<TtsModal
|
||||
open={ttsOpen}
|
||||
ttsOpen={ttsOpen}
|
||||
ttsText={ttsText}
|
||||
ttsVoiceId={ttsVoiceId}
|
||||
ttsSpeed={ttsSpeed}
|
||||
@@ -455,24 +270,16 @@ const VoiceLibrary: React.FC = () => {
|
||||
ttsAudioUrl={ttsAudioUrl}
|
||||
ttsError={ttsError}
|
||||
presetVoices={presetVoices}
|
||||
onClose={handleTtsClose}
|
||||
onTextChange={setTtsText}
|
||||
onVoiceChange={setTtsVoiceId}
|
||||
onSpeedChange={setTtsSpeed}
|
||||
onSynthesize={handleTtsSynthesize}
|
||||
onSave={handleTtsSave}
|
||||
onTtsClose={handleTtsClose}
|
||||
onTtsTextChange={setTtsText}
|
||||
onTtsVoiceChange={setTtsVoiceId}
|
||||
onTtsSpeedChange={setTtsSpeed}
|
||||
onTtsSynthesize={handleTtsSynthesize}
|
||||
onTtsSave={handleTtsSave}
|
||||
/>
|
||||
|
||||
{/* ── Toast 提示 ────────────────────────────────── */}
|
||||
{toasts.length > 0 && (
|
||||
<div className="vc-toast-container">
|
||||
{toasts.map((t) => (
|
||||
<div key={t.id} className={`vc-toast vc-toast--${t.type}`}>
|
||||
{t.type === "success" ? "✅" : "❌"} {t.message}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<VoiceToasts toasts={toasts} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* VoiceLibrary 我的克隆 Tab 内容
|
||||
*/
|
||||
import React from "react"
|
||||
import { UserOutlined, PlusOutlined, RobotOutlined } from "@ant-design/icons"
|
||||
import { Button } from "@/components/ui"
|
||||
import CloneVoiceCard from "./CloneVoiceCard"
|
||||
import CloneCardSkeleton from "./CloneCardSkeleton"
|
||||
import type { ClonedVoiceDisplay } from "../types"
|
||||
|
||||
export interface ClonedVoiceTabProps {
|
||||
loading: boolean
|
||||
voices: ClonedVoiceDisplay[]
|
||||
playingId: string | null
|
||||
currentTime: number
|
||||
onPlay: (voiceId: string, duration: number) => void
|
||||
onPause: () => void
|
||||
onUse: (voice: ClonedVoiceDisplay) => void
|
||||
onDelete: (voice: ClonedVoiceDisplay) => void
|
||||
onRetry: (voice: ClonedVoiceDisplay) => void
|
||||
onShowDetail: (voice: ClonedVoiceDisplay) => void
|
||||
onOpenClone: () => void
|
||||
}
|
||||
|
||||
export const ClonedVoiceTab: React.FC<ClonedVoiceTabProps> = ({
|
||||
loading,
|
||||
voices,
|
||||
playingId,
|
||||
currentTime,
|
||||
onPlay,
|
||||
onPause,
|
||||
onUse,
|
||||
onDelete,
|
||||
onRetry,
|
||||
onShowDetail,
|
||||
onOpenClone,
|
||||
}) => {
|
||||
return (
|
||||
<div className="xx-voices-tab-content">
|
||||
{/* 骨架屏加载 */}
|
||||
{loading && (
|
||||
<div className="xx-voice-grid">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<CloneCardSkeleton key={i} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 卡片列表 */}
|
||||
{!loading && voices.length > 0 && (
|
||||
<div className="xx-voice-grid">
|
||||
{voices.map((voice) => (
|
||||
<CloneVoiceCard
|
||||
key={voice.id}
|
||||
voice={voice}
|
||||
isPlaying={playingId === voice.id}
|
||||
currentTime={playingId === voice.id ? currentTime : 0}
|
||||
onPlay={() => onPlay(voice.id, voice.duration)}
|
||||
onPause={onPause}
|
||||
onUse={() => onUse(voice)}
|
||||
onDelete={() => onDelete(voice)}
|
||||
onRetry={() => onRetry(voice)}
|
||||
onShowDetail={() => onShowDetail(voice)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 空状态 */}
|
||||
{!loading && voices.length === 0 && (
|
||||
<div className="xx-voices-empty">
|
||||
<div className="xx-voices-empty-icon">
|
||||
<UserOutlined />
|
||||
</div>
|
||||
<h3>暂无克隆音色</h3>
|
||||
<p>上传音频素材即可克隆专属音色</p>
|
||||
<Button buttonType="primary" buttonSize="md" onClick={onOpenClone}>
|
||||
<PlusOutlined /> 去克隆音色
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 处理中提示 */}
|
||||
{!loading && voices.some((v) => v.status === "processing") && (
|
||||
<div className="xx-clone-processing-hint">
|
||||
<RobotOutlined />
|
||||
<span>部分音色正在克隆处理中,完成后将自动出现在列表中。</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ClonedVoiceTab
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* VoiceLibrary 配音素材 Tab 内容
|
||||
*/
|
||||
import React from "react"
|
||||
import { SoundOutlined, UploadOutlined, AudioOutlined } from "@ant-design/icons"
|
||||
import { Button } from "@/components/ui"
|
||||
import type { AssetItem } from "@/api/assets"
|
||||
|
||||
export interface MaterialVoiceTabProps {
|
||||
loading: boolean
|
||||
materials: AssetItem[]
|
||||
onOpenUpload: () => void
|
||||
}
|
||||
|
||||
export const MaterialVoiceTab: React.FC<MaterialVoiceTabProps> = ({
|
||||
loading,
|
||||
materials,
|
||||
onOpenUpload,
|
||||
}) => {
|
||||
return (
|
||||
<div className="xx-voices-tab-content">
|
||||
{/* 骨架屏加载 */}
|
||||
{loading && (
|
||||
<div className="xx-voice-grid">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<div key={i} className="vmat-card vmat-card--skeleton">
|
||||
<div className="vmat-thumb" />
|
||||
<div className="vmat-info">
|
||||
<div className="vmat-skeleton-line vmat-skeleton-title" />
|
||||
<div className="vmat-skeleton-line" />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 卡片列表 */}
|
||||
{!loading && materials.length > 0 && (
|
||||
<div className="xx-voice-grid">
|
||||
{materials.map((asset: AssetItem) => {
|
||||
const duration = (asset.metadata?.duration as number) || 0
|
||||
const minutes = Math.floor(duration / 60)
|
||||
const seconds = Math.floor(duration % 60)
|
||||
return (
|
||||
<div key={asset.id} className="vmat-card">
|
||||
<div className="vmat-thumb">
|
||||
<AudioOutlined className="vmat-thumb-icon" />
|
||||
<span className="vmat-duration">
|
||||
{minutes}:{seconds.toString().padStart(2, "0")}
|
||||
</span>
|
||||
</div>
|
||||
<div className="vmat-info">
|
||||
<div className="vmat-name" title={asset.name}>
|
||||
{asset.name}
|
||||
</div>
|
||||
<div className="vmat-meta">
|
||||
<span>
|
||||
{asset.file_size ? `${(asset.file_size / 1024 / 1024).toFixed(1)} MB` : "--"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 空状态 */}
|
||||
{!loading && materials.length === 0 && (
|
||||
<div className="xx-voices-empty">
|
||||
<div className="xx-voices-empty-icon">
|
||||
<SoundOutlined />
|
||||
</div>
|
||||
<h3>暂无配音素材</h3>
|
||||
<p>上传您的音频素材,用于视频配音</p>
|
||||
<Button buttonType="primary" buttonSize="md" onClick={onOpenUpload}>
|
||||
<UploadOutlined /> 上传音频
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default MaterialVoiceTab
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* VoiceLibrary 预置音色 Tab 内容
|
||||
*/
|
||||
import React from "react"
|
||||
import { SoundOutlined } from "@ant-design/icons"
|
||||
import { Button } from "@/components/ui"
|
||||
import VoiceFilterBar from "./VoiceFilterBar"
|
||||
import VoiceCard from "./VoiceCard"
|
||||
import { genderLabel, languageLabel } from "../utils/format"
|
||||
import type { PresetVoiceDisplay } from "../types"
|
||||
|
||||
export interface PresetVoiceTabProps {
|
||||
searchText: string
|
||||
filterGender: string
|
||||
filterLang: string
|
||||
onSearchChange: (text: string) => void
|
||||
onGenderChange: (gender: string) => void
|
||||
onLangChange: (lang: string) => void
|
||||
loading: boolean
|
||||
voices: PresetVoiceDisplay[]
|
||||
playingId: string | null
|
||||
currentTime: number
|
||||
onPlay: (id: string, duration: number) => void
|
||||
onPause: () => void
|
||||
onSeek: (id: string, time: number, duration: number) => void
|
||||
onClearFilters: () => void
|
||||
}
|
||||
|
||||
export const PresetVoiceTab: React.FC<PresetVoiceTabProps> = ({
|
||||
searchText,
|
||||
filterGender,
|
||||
filterLang,
|
||||
onSearchChange,
|
||||
onGenderChange,
|
||||
onLangChange,
|
||||
loading,
|
||||
voices,
|
||||
playingId,
|
||||
currentTime,
|
||||
onPlay,
|
||||
onPause,
|
||||
onSeek,
|
||||
onClearFilters,
|
||||
}) => {
|
||||
return (
|
||||
<div className="xx-voices-tab-content">
|
||||
<VoiceFilterBar
|
||||
searchText={searchText}
|
||||
filterGender={filterGender}
|
||||
filterLang={filterLang}
|
||||
onSearchChange={onSearchChange}
|
||||
onGenderChange={onGenderChange}
|
||||
onLangChange={onLangChange}
|
||||
/>
|
||||
|
||||
{loading && (
|
||||
<div className="xx-voices-empty">
|
||||
<div className="xx-voices-empty-icon">
|
||||
<SoundOutlined />
|
||||
</div>
|
||||
<p>加载预置音色中...</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && voices.length > 0 && (
|
||||
<div className="xx-voice-grid">
|
||||
{voices.map((voice) => (
|
||||
<VoiceCard
|
||||
key={voice.id}
|
||||
id={voice.id}
|
||||
name={voice.name}
|
||||
subtitle={`${genderLabel(voice.gender)} · ${languageLabel(voice.language)} · ${voice.description}`}
|
||||
tags={voice.tags}
|
||||
duration={voice.duration}
|
||||
gender={voice.gender}
|
||||
isPlaying={playingId === voice.id}
|
||||
isSelected={false}
|
||||
currentTime={playingId === voice.id ? currentTime : 0}
|
||||
starred={voice.starred}
|
||||
onPlay={() => onPlay(voice.id, voice.duration)}
|
||||
onPause={onPause}
|
||||
onSeek={(time) => onSeek(voice.id, time, voice.duration)}
|
||||
onToggleStar={() => {}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && voices.length === 0 && (
|
||||
<div className="xx-voices-empty">
|
||||
<div className="xx-voices-empty-icon">
|
||||
<SoundOutlined />
|
||||
</div>
|
||||
<p>未找到匹配的音色</p>
|
||||
<Button buttonType="ghost" buttonSize="sm" onClick={onClearFilters}>
|
||||
清除筛选条件
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default PresetVoiceTab
|
||||
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* VoiceLibrary 弹窗集合
|
||||
*/
|
||||
import React from "react"
|
||||
import type { ClonedVoiceDisplay, PresetVoiceDisplay, VoiceGender } from "../types"
|
||||
import type { VoiceClone } from "@/api/voice-clone"
|
||||
import type { TtsStatus } from "./TtsModal"
|
||||
import CloneModal from "@/components/voice/CloneModal"
|
||||
import CloneDetailModal from "./CloneDetailModal"
|
||||
import UploadVoiceModal from "./UploadVoiceModal"
|
||||
import TtsModal from "./TtsModal"
|
||||
|
||||
export interface VoiceModalsProps {
|
||||
/* 克隆音色弹窗 */
|
||||
cloneModalOpen: boolean
|
||||
onCloneClose: () => void
|
||||
onCloneSuccess: (voice: VoiceClone) => void
|
||||
|
||||
/* 克隆详情弹窗 */
|
||||
detailVoice: ClonedVoiceDisplay | null
|
||||
onDetailClose: () => void
|
||||
onDetailDelete: () => void
|
||||
onDetailRetry: () => void
|
||||
onDetailUse: () => void
|
||||
|
||||
/* 上传音频弹窗 */
|
||||
uploadOpen: boolean
|
||||
uploadFile: File | null
|
||||
uploadName: string
|
||||
uploadGender: VoiceGender
|
||||
uploadDesc: string
|
||||
uploadProgress: number | null
|
||||
onUploadClose: () => void
|
||||
onFileSelect: (file: File) => void
|
||||
onFileRemove: () => void
|
||||
onNameChange: (name: string) => void
|
||||
onGenderChange: (gender: VoiceGender) => void
|
||||
onDescChange: (desc: string) => void
|
||||
onUpload: () => void
|
||||
|
||||
/* TTS 弹窗 */
|
||||
ttsOpen: boolean
|
||||
ttsText: string
|
||||
ttsVoiceId: string
|
||||
ttsSpeed: number
|
||||
ttsStatus: TtsStatus
|
||||
ttsAudioUrl: string | null
|
||||
ttsError: string | null
|
||||
presetVoices: PresetVoiceDisplay[]
|
||||
onTtsClose: () => void
|
||||
onTtsTextChange: (text: string) => void
|
||||
onTtsVoiceChange: (id: string) => void
|
||||
onTtsSpeedChange: (speed: number) => void
|
||||
onTtsSynthesize: () => void
|
||||
onTtsSave: () => void
|
||||
}
|
||||
|
||||
export const VoiceModals: React.FC<VoiceModalsProps> = ({
|
||||
cloneModalOpen,
|
||||
onCloneClose,
|
||||
onCloneSuccess,
|
||||
detailVoice,
|
||||
onDetailClose,
|
||||
onDetailDelete,
|
||||
onDetailRetry,
|
||||
onDetailUse,
|
||||
uploadOpen,
|
||||
uploadFile,
|
||||
uploadName,
|
||||
uploadGender,
|
||||
uploadDesc,
|
||||
uploadProgress,
|
||||
onUploadClose,
|
||||
onFileSelect,
|
||||
onFileRemove,
|
||||
onNameChange,
|
||||
onGenderChange,
|
||||
onDescChange,
|
||||
onUpload,
|
||||
ttsOpen,
|
||||
ttsText,
|
||||
ttsVoiceId,
|
||||
ttsSpeed,
|
||||
ttsStatus,
|
||||
ttsAudioUrl,
|
||||
ttsError,
|
||||
presetVoices,
|
||||
onTtsClose,
|
||||
onTtsTextChange,
|
||||
onTtsVoiceChange,
|
||||
onTtsSpeedChange,
|
||||
onTtsSynthesize,
|
||||
onTtsSave,
|
||||
}) => {
|
||||
return (
|
||||
<>
|
||||
{/* 克隆音色弹窗 */}
|
||||
<CloneModal open={cloneModalOpen} onClose={onCloneClose} onSuccess={onCloneSuccess} />
|
||||
|
||||
{/* 详情弹窗 */}
|
||||
{detailVoice && (
|
||||
<CloneDetailModal
|
||||
voice={detailVoice}
|
||||
onClose={onDetailClose}
|
||||
onDelete={onDetailDelete}
|
||||
onRetry={onDetailRetry}
|
||||
onUse={onDetailUse}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 上传音频弹窗 */}
|
||||
<UploadVoiceModal
|
||||
open={uploadOpen}
|
||||
uploadFile={uploadFile}
|
||||
uploadName={uploadName}
|
||||
uploadGender={uploadGender}
|
||||
uploadDesc={uploadDesc}
|
||||
uploadProgress={uploadProgress}
|
||||
onClose={onUploadClose}
|
||||
onFileSelect={onFileSelect}
|
||||
onFileRemove={onFileRemove}
|
||||
onNameChange={onNameChange}
|
||||
onGenderChange={onGenderChange}
|
||||
onDescChange={onDescChange}
|
||||
onUpload={onUpload}
|
||||
/>
|
||||
|
||||
{/* AI 配音弹窗 */}
|
||||
<TtsModal
|
||||
open={ttsOpen}
|
||||
ttsText={ttsText}
|
||||
ttsVoiceId={ttsVoiceId}
|
||||
ttsSpeed={ttsSpeed}
|
||||
ttsStatus={ttsStatus}
|
||||
ttsAudioUrl={ttsAudioUrl}
|
||||
ttsError={ttsError}
|
||||
presetVoices={presetVoices}
|
||||
onClose={onTtsClose}
|
||||
onTextChange={onTtsTextChange}
|
||||
onVoiceChange={onTtsVoiceChange}
|
||||
onSpeedChange={onTtsSpeedChange}
|
||||
onSynthesize={onTtsSynthesize}
|
||||
onSave={onTtsSave}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default VoiceModals
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* VoiceLibrary Tab 切换栏
|
||||
*/
|
||||
import React from "react"
|
||||
import { AudioOutlined, UserOutlined, SoundOutlined } from "@ant-design/icons"
|
||||
|
||||
export type VoiceTabKey = "preset" | "cloned" | "material"
|
||||
|
||||
export interface VoiceTabBarProps {
|
||||
activeTab: VoiceTabKey
|
||||
presetCount: number
|
||||
cloneCount: number
|
||||
materialCount: number
|
||||
onTabChange: (tab: VoiceTabKey) => void
|
||||
}
|
||||
|
||||
export const VoiceTabBar: React.FC<VoiceTabBarProps> = ({
|
||||
activeTab,
|
||||
presetCount,
|
||||
cloneCount,
|
||||
materialCount,
|
||||
onTabChange,
|
||||
}) => {
|
||||
return (
|
||||
<div className="xx-voices-tabs">
|
||||
<button
|
||||
className={`xx-voices-tab${activeTab === "preset" ? " active" : ""}`}
|
||||
onClick={() => onTabChange("preset")}
|
||||
>
|
||||
<AudioOutlined />
|
||||
预置音色
|
||||
<span className="xx-voices-tab-count">{presetCount}</span>
|
||||
</button>
|
||||
<button
|
||||
className={`xx-voices-tab${activeTab === "cloned" ? " active" : ""}`}
|
||||
onClick={() => onTabChange("cloned")}
|
||||
>
|
||||
<UserOutlined />
|
||||
我的克隆
|
||||
<span className="xx-voices-tab-count">{cloneCount}</span>
|
||||
</button>
|
||||
<button
|
||||
className={`xx-voices-tab${activeTab === "material" ? " active" : ""}`}
|
||||
onClick={() => onTabChange("material")}
|
||||
>
|
||||
<SoundOutlined />
|
||||
配音素材
|
||||
<span className="xx-voices-tab-count">{materialCount}</span>
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default VoiceTabBar
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* VoiceLibrary Toast 提示
|
||||
*/
|
||||
import React from "react"
|
||||
|
||||
export interface Toast {
|
||||
id: number
|
||||
message: string
|
||||
type: "success" | "error"
|
||||
}
|
||||
|
||||
export interface VoiceToastsProps {
|
||||
toasts: Toast[]
|
||||
}
|
||||
|
||||
export const VoiceToasts: React.FC<VoiceToastsProps> = ({ toasts }) => {
|
||||
if (toasts.length === 0) return null
|
||||
return (
|
||||
<div className="vc-toast-container">
|
||||
{toasts.map((t) => (
|
||||
<div key={t.id} className={`vc-toast vc-toast--${t.type}`}>
|
||||
{t.type === "success" ? "✅" : "❌"} {t.message}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default VoiceToasts
|
||||
@@ -1,4 +1,4 @@
|
||||
"""视频调速引擎 — 基于 FFmpeg setpts + atempo 的速度调整能力。
|
||||
"""视频调速引擎 — 基于 FFmpeg setpts + atempo 的速度调整能力.
|
||||
|
||||
支持:
|
||||
- 0.25x ~ 4x 变速范围
|
||||
@@ -6,147 +6,57 @@
|
||||
- 音频调速(atempo,多级串联处理超范围值)
|
||||
- 音调修正(pitch_correct,默认开启)
|
||||
- 边界自动钳制,不阻断渲染
|
||||
|
||||
注:核心领域模型已抽离到 packages/domain/speed_config.py,
|
||||
本模块保留薄包装层,确保向后兼容。
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
# ─── 常量 ───────────────────────────────────────────────
|
||||
MIN_SPEED = 0.25
|
||||
MAX_SPEED = 4.0
|
||||
DEFAULT_SPEED = 1.0
|
||||
|
||||
# atempo 单级有效范围
|
||||
_ATEMPO_MIN = 0.5
|
||||
_ATEMPO_MAX = 2.0
|
||||
|
||||
|
||||
@dataclass
|
||||
class SpeedConfig:
|
||||
"""调速配置。
|
||||
|
||||
Attributes:
|
||||
speed: 播放速度,0.25~4.0,1.0 为原速
|
||||
pitch_correct: 是否保持音调(默认 True,用 atempo 时间拉伸算法)
|
||||
"""
|
||||
|
||||
speed: float = DEFAULT_SPEED
|
||||
pitch_correct: bool = True
|
||||
|
||||
@classmethod
|
||||
def parse(cls, data: Optional[dict]) -> "SpeedConfig":
|
||||
"""从 dict 解析配置,无效值回退到默认。"""
|
||||
if not data or not isinstance(data, dict):
|
||||
return cls()
|
||||
|
||||
speed = data.get("speed", DEFAULT_SPEED)
|
||||
if not isinstance(speed, (int, float)):
|
||||
speed = DEFAULT_SPEED
|
||||
|
||||
pitch_correct = data.get("pitch_correct", True)
|
||||
if not isinstance(pitch_correct, bool):
|
||||
pitch_correct = True
|
||||
|
||||
config = cls(speed=float(speed), pitch_correct=pitch_correct)
|
||||
config.clamp()
|
||||
return config
|
||||
|
||||
def clamp(self) -> None:
|
||||
"""将速度钳制到合法范围。"""
|
||||
if self.speed <= 0:
|
||||
self.speed = DEFAULT_SPEED
|
||||
elif self.speed < MIN_SPEED:
|
||||
self.speed = MIN_SPEED
|
||||
elif self.speed > MAX_SPEED:
|
||||
self.speed = MAX_SPEED
|
||||
|
||||
@property
|
||||
def is_original(self) -> bool:
|
||||
"""是否原速(无需调速)。"""
|
||||
return abs(self.speed - 1.0) < 1e-6
|
||||
from packages.domain.speed_config import ( # noqa: F401 — 向后兼容
|
||||
DEFAULT_SPEED,
|
||||
MAX_SPEED,
|
||||
MIN_SPEED,
|
||||
SpeedConfig,
|
||||
_split_atempo_stages,
|
||||
adjust_duration as _adjust_duration_base,
|
||||
build_audio_filter as _build_audio_filter_base,
|
||||
build_video_filter as _build_video_filter_base,
|
||||
resolve_clip_speed as _resolve_clip_speed_base,
|
||||
)
|
||||
|
||||
|
||||
class SpeedEngine:
|
||||
"""调速引擎 — 生成 FFmpeg 调速滤镜链。
|
||||
"""调速引擎 — 生成 FFmpeg 调速滤镜链.
|
||||
|
||||
用法:
|
||||
engine = SpeedEngine()
|
||||
video_filter = engine.build_video_filter(config)
|
||||
audio_filter = engine.build_audio_filter(config)
|
||||
new_duration = engine.adjust_duration(duration, config)
|
||||
薄包装层,实际逻辑委托给 packages.domain.speed_config。
|
||||
"""
|
||||
|
||||
def build_video_filter(self, config: SpeedConfig) -> str:
|
||||
"""生成视频调速滤镜字符串。
|
||||
|
||||
返回 setpts 滤镜表达式,原速时返回空字符串。
|
||||
"""
|
||||
if config.is_original:
|
||||
return ""
|
||||
# setpts=PTS/speed — speed>1 加速,speed<1 减速
|
||||
return f"setpts=PTS/{config.speed:.4f}"
|
||||
"""生成视频调速滤镜字符串."""
|
||||
return _build_video_filter_base(config)
|
||||
|
||||
def build_audio_filter(self, config: SpeedConfig) -> str:
|
||||
"""生成音频调速滤镜字符串。
|
||||
|
||||
atempo 单级范围 0.5~2.0,超出范围时自动多级串联:
|
||||
- 0.25x → atempo=0.5,atempo=0.5
|
||||
- 4x → atempo=2.0,atempo=2.0
|
||||
- 0.3x → atempo=0.5,atempo=0.6
|
||||
- 3x → atempo=2.0,atempo=1.5
|
||||
|
||||
原速时返回空字符串。
|
||||
"""
|
||||
if config.is_original:
|
||||
return ""
|
||||
|
||||
speed = config.speed
|
||||
stages: list[float] = self._split_atempo_stages(speed)
|
||||
return ",".join(f"atempo={s:.4f}" for s in stages)
|
||||
"""生成音频调速滤镜字符串."""
|
||||
return _build_audio_filter_base(config)
|
||||
|
||||
@staticmethod
|
||||
def _split_atempo_stages(speed: float) -> list[float]:
|
||||
"""将速度拆分为多级 atempo 串联,每级都在 [0.5, 2.0] 范围内。"""
|
||||
if _ATEMPO_MIN <= speed <= _ATEMPO_MAX:
|
||||
return [speed]
|
||||
|
||||
stages: list[float] = []
|
||||
remaining = speed
|
||||
|
||||
# 加速场景(speed > 2.0)
|
||||
if speed > _ATEMPO_MAX:
|
||||
while remaining > _ATEMPO_MAX:
|
||||
stages.append(_ATEMPO_MAX)
|
||||
remaining /= _ATEMPO_MAX
|
||||
stages.append(remaining)
|
||||
|
||||
# 减速场景(speed < 0.5)
|
||||
else:
|
||||
while remaining < _ATEMPO_MIN:
|
||||
stages.append(_ATEMPO_MIN)
|
||||
remaining /= _ATEMPO_MIN
|
||||
stages.append(remaining)
|
||||
|
||||
return stages
|
||||
"""将速度拆分为多级 atempo 串联(内部方法,向后兼容)."""
|
||||
return _split_atempo_stages(speed)
|
||||
|
||||
def adjust_duration(self, original_duration: float, config: SpeedConfig) -> float:
|
||||
"""计算调速后的时长。
|
||||
|
||||
加速 → 时长变短;减速 → 时长变长。
|
||||
"""
|
||||
if config.is_original or original_duration <= 0:
|
||||
return original_duration
|
||||
return original_duration / config.speed
|
||||
"""计算调速后的时长."""
|
||||
return _adjust_duration_base(original_duration, config)
|
||||
|
||||
def build_clip_speed_filter(
|
||||
self,
|
||||
speed: float,
|
||||
pitch_correct: bool = True,
|
||||
) -> tuple[str, str, SpeedConfig]:
|
||||
"""便捷方法:从单一 speed 值生成视频+音频滤镜。
|
||||
|
||||
返回 (video_filter, audio_filter, config)。
|
||||
"""
|
||||
"""便捷方法:从单一 speed 值生成视频+音频滤镜."""
|
||||
config = SpeedConfig(speed=speed, pitch_correct=pitch_correct)
|
||||
config.clamp()
|
||||
return (
|
||||
@@ -160,8 +70,5 @@ class SpeedEngine:
|
||||
clip_config: dict,
|
||||
global_speed: float = DEFAULT_SPEED,
|
||||
) -> float:
|
||||
"""从 clip config 中解析 playback_speed,0 或缺失则使用全局速度。"""
|
||||
speed = clip_config.get("playback_speed", 0) if clip_config else 0
|
||||
if not isinstance(speed, (int, float)) or speed <= 0:
|
||||
return global_speed
|
||||
return float(speed)
|
||||
"""从 clip config 中解析 playback_speed,0 或缺失则使用全局速度."""
|
||||
return _resolve_clip_speed_base(clip_config, global_speed)
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
"""调速配置领域模型 — 纯逻辑,无FFmpeg依赖.
|
||||
|
||||
抽离自 speed_engine.py,包含:
|
||||
- SpeedConfig 数据类(解析/钳制/原速判断)
|
||||
- 视频/音频调速滤镜构建
|
||||
- atempo 多级拆分算法
|
||||
- 时长计算
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
# ─── 常量 ───────────────────────────────────────────────
|
||||
MIN_SPEED = 0.25
|
||||
MAX_SPEED = 4.0
|
||||
DEFAULT_SPEED = 1.0
|
||||
|
||||
# atempo 单级有效范围
|
||||
_ATEMPO_MIN = 0.5
|
||||
_ATEMPO_MAX = 2.0
|
||||
|
||||
|
||||
@dataclass
|
||||
class SpeedConfig:
|
||||
"""调速配置.
|
||||
|
||||
Attributes:
|
||||
speed: 播放速度,0.25~4.0,1.0 为原速
|
||||
pitch_correct: 是否保持音调(默认 True,用 atempo 时间拉伸算法)
|
||||
"""
|
||||
|
||||
speed: float = DEFAULT_SPEED
|
||||
pitch_correct: bool = True
|
||||
|
||||
@classmethod
|
||||
def parse(cls, data: dict[str, Any] | None) -> SpeedConfig:
|
||||
"""从 dict 解析配置,无效值回退到默认."""
|
||||
if not data or not isinstance(data, dict):
|
||||
return cls()
|
||||
|
||||
speed = data.get("speed", DEFAULT_SPEED)
|
||||
if not isinstance(speed, (int, float)):
|
||||
speed = DEFAULT_SPEED
|
||||
|
||||
pitch_correct = data.get("pitch_correct", True)
|
||||
if not isinstance(pitch_correct, bool):
|
||||
pitch_correct = True
|
||||
|
||||
config = cls(speed=float(speed), pitch_correct=pitch_correct)
|
||||
config.clamp()
|
||||
return config
|
||||
|
||||
def clamp(self) -> None:
|
||||
"""将速度钳制到合法范围."""
|
||||
if self.speed <= 0:
|
||||
self.speed = DEFAULT_SPEED
|
||||
elif self.speed < MIN_SPEED:
|
||||
self.speed = MIN_SPEED
|
||||
elif self.speed > MAX_SPEED:
|
||||
self.speed = MAX_SPEED
|
||||
|
||||
@property
|
||||
def is_original(self) -> bool:
|
||||
"""是否原速(无需调速)."""
|
||||
return abs(self.speed - 1.0) < 1e-6
|
||||
|
||||
@property
|
||||
def is_fast(self) -> bool:
|
||||
"""是否加速播放."""
|
||||
return self.speed > 1.0
|
||||
|
||||
@property
|
||||
def is_slow(self) -> bool:
|
||||
"""是否减速播放."""
|
||||
return self.speed < 1.0
|
||||
|
||||
|
||||
# ── 滤镜构建 ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def build_video_filter(config: SpeedConfig) -> str:
|
||||
"""生成视频调速滤镜字符串.
|
||||
|
||||
返回 setpts 滤镜表达式,原速时返回空字符串。
|
||||
"""
|
||||
if config.is_original:
|
||||
return ""
|
||||
# setpts=PTS/speed — speed>1 加速,speed<1 减速
|
||||
return f"setpts=PTS/{config.speed:.4f}"
|
||||
|
||||
|
||||
def build_audio_filter(config: SpeedConfig) -> str:
|
||||
"""生成音频调速滤镜字符串.
|
||||
|
||||
atempo 单级范围 0.5~2.0,超出范围时自动多级串联:
|
||||
- 0.25x → atempo=0.5,atempo=0.5
|
||||
- 4x → atempo=2.0,atempo=2.0
|
||||
- 0.3x → atempo=0.5,atempo=0.6
|
||||
- 3x → atempo=2.0,atempo=1.5
|
||||
|
||||
原速时返回空字符串。
|
||||
"""
|
||||
if config.is_original:
|
||||
return ""
|
||||
|
||||
speed = config.speed
|
||||
stages: list[float] = _split_atempo_stages(speed)
|
||||
return ",".join(f"atempo={s:.4f}" for s in stages)
|
||||
|
||||
|
||||
def _split_atempo_stages(speed: float) -> list[float]:
|
||||
"""将速度拆分为多级 atempo 串联,每级都在 [0.5, 2.0] 范围内."""
|
||||
if _ATEMPO_MIN <= speed <= _ATEMPO_MAX:
|
||||
return [speed]
|
||||
|
||||
stages: list[float] = []
|
||||
remaining = speed
|
||||
|
||||
# 加速场景(speed > 2.0)
|
||||
if speed > _ATEMPO_MAX:
|
||||
while remaining > _ATEMPO_MAX:
|
||||
stages.append(_ATEMPO_MAX)
|
||||
remaining /= _ATEMPO_MAX
|
||||
stages.append(remaining)
|
||||
|
||||
# 减速场景(speed < 0.5)
|
||||
else:
|
||||
while remaining < _ATEMPO_MIN:
|
||||
stages.append(_ATEMPO_MIN)
|
||||
remaining /= _ATEMPO_MIN
|
||||
stages.append(remaining)
|
||||
|
||||
return stages
|
||||
|
||||
|
||||
# ── 时长计算 ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def adjust_duration(original_duration: float, config: SpeedConfig) -> float:
|
||||
"""计算调速后的时长.
|
||||
|
||||
加速 → 时长变短;减速 → 时长变长。
|
||||
"""
|
||||
if config.is_original or original_duration <= 0:
|
||||
return original_duration
|
||||
return original_duration / config.speed
|
||||
|
||||
|
||||
# ── 便捷方法 ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def build_clip_speed_filter(
|
||||
speed: float,
|
||||
pitch_correct: bool = True,
|
||||
) -> tuple[str, str, SpeedConfig]:
|
||||
"""便捷方法:从单一 speed 值生成视频+音频滤镜.
|
||||
|
||||
返回 (video_filter, audio_filter, config)。
|
||||
"""
|
||||
config = SpeedConfig(speed=speed, pitch_correct=pitch_correct)
|
||||
config.clamp()
|
||||
return (
|
||||
build_video_filter(config),
|
||||
build_audio_filter(config),
|
||||
config,
|
||||
)
|
||||
|
||||
|
||||
def resolve_clip_speed(
|
||||
clip_config: dict[str, Any] | None,
|
||||
global_speed: float = DEFAULT_SPEED,
|
||||
) -> float:
|
||||
"""从 clip config 中解析 playback_speed,0 或缺失则使用全局速度."""
|
||||
speed = clip_config.get("playback_speed", 0) if clip_config else 0
|
||||
if not isinstance(speed, (int, float)) or speed <= 0:
|
||||
return global_speed
|
||||
return float(speed)
|
||||
@@ -0,0 +1,313 @@
|
||||
"""speed_config 领域模型单测."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from packages.domain.speed_config import (
|
||||
DEFAULT_SPEED,
|
||||
MAX_SPEED,
|
||||
MIN_SPEED,
|
||||
SpeedConfig,
|
||||
adjust_duration,
|
||||
build_audio_filter,
|
||||
build_video_filter,
|
||||
build_clip_speed_filter,
|
||||
resolve_clip_speed,
|
||||
)
|
||||
|
||||
# ── 常量测试 ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestConstants:
|
||||
def test_min_speed(self):
|
||||
assert MIN_SPEED == 0.25
|
||||
|
||||
def test_max_speed(self):
|
||||
assert MAX_SPEED == 4.0
|
||||
|
||||
def test_default_speed(self):
|
||||
assert DEFAULT_SPEED == 1.0
|
||||
|
||||
|
||||
# ── SpeedConfig.parse 测试 ────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestSpeedConfigParse:
|
||||
def test_none_returns_default(self):
|
||||
cfg = SpeedConfig.parse(None)
|
||||
assert cfg.speed == DEFAULT_SPEED
|
||||
assert cfg.pitch_correct is True
|
||||
|
||||
def test_empty_dict_returns_default(self):
|
||||
cfg = SpeedConfig.parse({})
|
||||
assert cfg.speed == DEFAULT_SPEED
|
||||
|
||||
def test_invalid_type_returns_default(self):
|
||||
cfg = SpeedConfig.parse("not_a_dict")
|
||||
assert cfg.speed == DEFAULT_SPEED
|
||||
|
||||
def test_valid_speed(self):
|
||||
cfg = SpeedConfig.parse({"speed": 2.0})
|
||||
assert cfg.speed == 2.0
|
||||
|
||||
def test_speed_clamped_low(self):
|
||||
cfg = SpeedConfig.parse({"speed": 0.1})
|
||||
assert cfg.speed == MIN_SPEED
|
||||
|
||||
def test_speed_clamped_high(self):
|
||||
cfg = SpeedConfig.parse({"speed": 5.0})
|
||||
assert cfg.speed == MAX_SPEED
|
||||
|
||||
def test_zero_speed_returns_default(self):
|
||||
cfg = SpeedConfig.parse({"speed": 0})
|
||||
assert cfg.speed == DEFAULT_SPEED
|
||||
|
||||
def test_negative_speed_returns_default(self):
|
||||
cfg = SpeedConfig.parse({"speed": -1.0})
|
||||
assert cfg.speed == DEFAULT_SPEED
|
||||
|
||||
def test_pitch_correct_false(self):
|
||||
cfg = SpeedConfig.parse({"pitch_correct": False})
|
||||
assert cfg.pitch_correct is False
|
||||
|
||||
def test_pitch_correct_invalid_type_defaults_true(self):
|
||||
cfg = SpeedConfig.parse({"pitch_correct": "yes"})
|
||||
assert cfg.pitch_correct is True
|
||||
|
||||
def test_string_speed_invalid_uses_default(self):
|
||||
cfg = SpeedConfig.parse({"speed": "fast"})
|
||||
assert cfg.speed == DEFAULT_SPEED
|
||||
|
||||
|
||||
# ── SpeedConfig.clamp 测试 ────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestClamp:
|
||||
def test_already_valid_unchanged(self):
|
||||
cfg = SpeedConfig(speed=1.5)
|
||||
cfg.clamp()
|
||||
assert cfg.speed == 1.5
|
||||
|
||||
def test_below_min_clamped(self):
|
||||
cfg = SpeedConfig(speed=0.1)
|
||||
cfg.clamp()
|
||||
assert cfg.speed == MIN_SPEED
|
||||
|
||||
def test_above_max_clamped(self):
|
||||
cfg = SpeedConfig(speed=10.0)
|
||||
cfg.clamp()
|
||||
assert cfg.speed == MAX_SPEED
|
||||
|
||||
def test_zero_defaults(self):
|
||||
cfg = SpeedConfig(speed=0.0)
|
||||
cfg.clamp()
|
||||
assert cfg.speed == DEFAULT_SPEED
|
||||
|
||||
def test_negative_defaults(self):
|
||||
cfg = SpeedConfig(speed=-2.0)
|
||||
cfg.clamp()
|
||||
assert cfg.speed == DEFAULT_SPEED
|
||||
|
||||
def test_exact_min_stays(self):
|
||||
cfg = SpeedConfig(speed=MIN_SPEED)
|
||||
cfg.clamp()
|
||||
assert cfg.speed == MIN_SPEED
|
||||
|
||||
def test_exact_max_stays(self):
|
||||
cfg = SpeedConfig(speed=MAX_SPEED)
|
||||
cfg.clamp()
|
||||
assert cfg.speed == MAX_SPEED
|
||||
|
||||
|
||||
# ── is_original / is_fast / is_slow 测试 ─────────────────────────────────
|
||||
|
||||
|
||||
class TestSpeedProperties:
|
||||
def test_is_original_true(self):
|
||||
cfg = SpeedConfig(speed=1.0)
|
||||
assert cfg.is_original is True
|
||||
|
||||
def test_is_original_false_fast(self):
|
||||
cfg = SpeedConfig(speed=2.0)
|
||||
assert cfg.is_original is False
|
||||
|
||||
def test_is_original_false_slow(self):
|
||||
cfg = SpeedConfig(speed=0.5)
|
||||
assert cfg.is_original is False
|
||||
|
||||
def test_is_original_near_one(self):
|
||||
cfg = SpeedConfig(speed=1.0000001)
|
||||
assert cfg.is_original is True
|
||||
|
||||
def test_is_fast_true(self):
|
||||
cfg = SpeedConfig(speed=2.0)
|
||||
assert cfg.is_fast is True
|
||||
|
||||
def test_is_fast_false(self):
|
||||
cfg = SpeedConfig(speed=0.5)
|
||||
assert cfg.is_fast is False
|
||||
|
||||
def test_is_false_for_original(self):
|
||||
cfg = SpeedConfig(speed=1.0)
|
||||
assert cfg.is_fast is False
|
||||
assert cfg.is_slow is False
|
||||
|
||||
def test_is_slow_true(self):
|
||||
cfg = SpeedConfig(speed=0.5)
|
||||
assert cfg.is_slow is True
|
||||
|
||||
def test_is_slow_false(self):
|
||||
cfg = SpeedConfig(speed=2.0)
|
||||
assert cfg.is_slow is False
|
||||
|
||||
|
||||
# ── build_video_filter 测试 ───────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestBuildVideoFilter:
|
||||
def test_original_speed_empty(self):
|
||||
cfg = SpeedConfig(speed=1.0)
|
||||
assert build_video_filter(cfg) == ""
|
||||
|
||||
def test_fast_speed_setpts(self):
|
||||
cfg = SpeedConfig(speed=2.0)
|
||||
result = build_video_filter(cfg)
|
||||
assert "setpts=PTS/2.0000" in result
|
||||
|
||||
def test_slow_speed_setpts(self):
|
||||
cfg = SpeedConfig(speed=0.5)
|
||||
result = build_video_filter(cfg)
|
||||
assert "setpts=PTS/0.5000" in result
|
||||
|
||||
def test_format_four_decimals(self):
|
||||
cfg = SpeedConfig(speed=1.5)
|
||||
result = build_video_filter(cfg)
|
||||
assert "1.5000" in result
|
||||
|
||||
|
||||
# ── build_audio_filter 测试 ───────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestBuildAudioFilter:
|
||||
def test_original_speed_empty(self):
|
||||
cfg = SpeedConfig(speed=1.0)
|
||||
assert build_audio_filter(cfg) == ""
|
||||
|
||||
def test_single_stage_within_range(self):
|
||||
cfg = SpeedConfig(speed=1.5)
|
||||
result = build_audio_filter(cfg)
|
||||
assert result == "atempo=1.5000"
|
||||
assert result.count("atempo") == 1
|
||||
|
||||
def test_fast_two_stages(self):
|
||||
cfg = SpeedConfig(speed=3.0)
|
||||
result = build_audio_filter(cfg)
|
||||
assert result.count("atempo") == 2
|
||||
# 2.0 * 1.5 = 3.0
|
||||
assert "atempo=2.0000" in result
|
||||
assert "atempo=1.5000" in result
|
||||
|
||||
def test_max_speed_two_stages(self):
|
||||
cfg = SpeedConfig(speed=4.0)
|
||||
result = build_audio_filter(cfg)
|
||||
assert result.count("atempo") == 2
|
||||
# 2.0 * 2.0 = 4.0
|
||||
assert result == "atempo=2.0000,atempo=2.0000"
|
||||
|
||||
def test_slow_two_stages(self):
|
||||
cfg = SpeedConfig(speed=0.25)
|
||||
result = build_audio_filter(cfg)
|
||||
assert result.count("atempo") == 2
|
||||
# 0.5 * 0.5 = 0.25
|
||||
assert result == "atempo=0.5000,atempo=0.5000"
|
||||
|
||||
def test_slow_single_stage(self):
|
||||
cfg = SpeedConfig(speed=0.8)
|
||||
result = build_audio_filter(cfg)
|
||||
assert result == "atempo=0.8000"
|
||||
assert result.count("atempo") == 1
|
||||
|
||||
def test_exactly_two_point_zero_single(self):
|
||||
cfg = SpeedConfig(speed=2.0)
|
||||
result = build_audio_filter(cfg)
|
||||
assert result.count("atempo") == 1
|
||||
assert "atempo=2.0000" in result
|
||||
|
||||
def test_exactly_half_single(self):
|
||||
cfg = SpeedConfig(speed=0.5)
|
||||
result = build_audio_filter(cfg)
|
||||
assert result.count("atempo") == 1
|
||||
assert "atempo=0.5000" in result
|
||||
|
||||
|
||||
# ── adjust_duration 测试 ──────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestAdjustDuration:
|
||||
def test_original_speed_unchanged(self):
|
||||
cfg = SpeedConfig(speed=1.0)
|
||||
assert adjust_duration(10.0, cfg) == 10.0
|
||||
|
||||
def test_double_speed_halved(self):
|
||||
cfg = SpeedConfig(speed=2.0)
|
||||
assert adjust_duration(10.0, cfg) == 5.0
|
||||
|
||||
def test_half_speed_doubled(self):
|
||||
cfg = SpeedConfig(speed=0.5)
|
||||
assert adjust_duration(10.0, cfg) == 20.0
|
||||
|
||||
def test_zero_duration_unchanged(self):
|
||||
cfg = SpeedConfig(speed=2.0)
|
||||
assert adjust_duration(0.0, cfg) == 0.0
|
||||
|
||||
def test_negative_duration_unchanged(self):
|
||||
cfg = SpeedConfig(speed=2.0)
|
||||
assert adjust_duration(-5.0, cfg) == -5.0
|
||||
|
||||
|
||||
# ── build_clip_speed_filter 测试 ─────────────────────────────────────────
|
||||
|
||||
|
||||
class TestBuildClipSpeedFilter:
|
||||
def test_normal_speed(self):
|
||||
vf, af, cfg = build_clip_speed_filter(2.0)
|
||||
assert vf == "setpts=PTS/2.0000"
|
||||
assert "atempo=2.0000" in af
|
||||
assert cfg.speed == 2.0
|
||||
|
||||
def test_clamped_speed(self):
|
||||
vf, af, cfg = build_clip_speed_filter(10.0)
|
||||
assert cfg.speed == MAX_SPEED
|
||||
|
||||
def test_pitch_correct_param(self):
|
||||
vf, af, cfg = build_clip_speed_filter(1.5, pitch_correct=False)
|
||||
assert cfg.pitch_correct is False
|
||||
|
||||
def test_original_speed_empty_filters(self):
|
||||
vf, af, cfg = build_clip_speed_filter(1.0)
|
||||
assert vf == ""
|
||||
assert af == ""
|
||||
|
||||
|
||||
# ── resolve_clip_speed 测试 ──────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestResolveClipSpeed:
|
||||
def test_none_config_uses_global(self):
|
||||
assert resolve_clip_speed(None, 1.5) == 1.5
|
||||
|
||||
def test_no_playback_speed_uses_global(self):
|
||||
assert resolve_clip_speed({}, 1.5) == 1.5
|
||||
|
||||
def test_zero_speed_uses_global(self):
|
||||
assert resolve_clip_speed({"playback_speed": 0}, 1.5) == 1.5
|
||||
|
||||
def test_valid_speed_returns_speed(self):
|
||||
assert resolve_clip_speed({"playback_speed": 2.0}, 1.0) == 2.0
|
||||
|
||||
def test_invalid_type_uses_global(self):
|
||||
assert resolve_clip_speed({"playback_speed": "fast"}, 1.0) == 1.0
|
||||
|
||||
def test_default_global_speed(self):
|
||||
assert resolve_clip_speed({}) == DEFAULT_SPEED
|
||||
Reference in New Issue
Block a user