Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
feat(editor): import audio onto the timeline with a lane and inspector
Benjamin Freemanb218f4a8ab82
diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsxindex 5b7792afe..ae4297378 100644--- a/src/components/ai-edition/RightPanes.tsx+++ b/src/components/ai-edition/RightPanes.tsx@@ -13,8 +13,11 @@ import {Layout as LayoutIcon,Loader2,MousePointerClick,+ Music,Sliders,Trash2,+ Volume2,+ VolumeX,} from "lucide-react";import {@@ -52,6 +55,7 @@ import {} from "@/lib/ai-edition/store/editorSettings";import { useProjectStore } from "@/lib/ai-edition/store/projectStore";import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";+import type { useTimeline } from "@/lib/ai-edition/store/useTimeline";import {buildAggregatedSections,type ClipSection,@@ -2332,6 +2336,105 @@ export function AudioPane() {);}+type TimelineApi = ReturnType<typeof useTimeline>;++// Per-track controls for the selected imported audio track (issue #350). Shown by+// the inspector in place of the facet when an audio track is selected (see+// FloatingInspector). Volume drives a local live value during the drag and only+// writes (one undo step) on release, the same shape as the global output-gain+// slider; mute / offset / remove each write once.+export function AudioTrackPane({ tl }: { tl: TimelineApi }) {+ const ts = useScopedT("settings");+ const trackId = tl.selectedAudioTrackId;+ const track = tl.audioTracks.find((t) => t.id === trackId);+ const asset = track ? tl.assets.find((a) => a.id === track.assetId) : undefined;+ // Live-drag value for the volume slider; null means "show the committed gain".+ const [liveGain, setLiveGain] = useState<number | null>(null);+ // Draft text for the offset field; null means "show the track's real offset".+ const [offsetDraft, setOffsetDraft] = useState<string | null>(null);+ if (!track) return null;+ const label = track.label || asset?.label || ts("audioTrack.defaultLabel");++ const commitOffset = () => {+ if (offsetDraft === null) return;+ const parsed = Number.parseFloat(offsetDraft);+ if (Number.isFinite(parsed)) void tl.moveAudioTrack(track.id, Math.max(0, parsed));+ setOffsetDraft(null);+ };++ return (+ <Pane title={label} icon={<Music size={14} />} helpText={ts("audioTrack.help")}>+ <div className={styles.sliderGrid}>+ <SliderCell+ label={ts("audioTrack.volume")}+ value={liveGain ?? track.gainDb}+ min={-AUDIO_GAIN_DB_LIMIT}+ max={AUDIO_GAIN_DB_LIMIT}+ step={0.5}+ decimals={1}+ suffix=" dB"+ disabled={track.mute}+ onChange={(value) => setLiveGain(value)}+ onCommit={() => {+ if (liveGain !== null) void tl.setAudioTrackGain(track.id, liveGain);+ setLiveGain(null);+ }}+ />+ </div>+ <label+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "space-between",+ gap: 8,+ fontSize: 12,+ color: "var(--meta)",+ margin: "2px 0 8px",+ }}+ >+ <span>{ts("audioTrack.offset")}</span>+ <input+ type="number"+ min={0}+ step={0.1}+ value={offsetDraft ?? track.timelineStartSec.toFixed(2)}+ onChange={(e) => setOffsetDraft(e.target.value)}+ onBlur={commitOffset}+ onKeyDown={(e) => {+ if (e.key === "Enter") e.currentTarget.blur();+ }}+ style={{+ width: 84,+ padding: "4px 6px",+ background: "var(--surface-warm)",+ border: "1px solid var(--border-soft)",+ borderRadius: "var(--r-sm)",+ color: "var(--fg)",+ font: "12px var(--font-body)",+ textAlign: "right",+ }}+ />+ </label>+ <button+ type="button"+ className={styles.secondaryBtn}+ onClick={() => void tl.toggleAudioTrackMute(track.id)}+ >+ {track.mute ? <VolumeX size={14} /> : <Volume2 size={14} />}+ {track.mute ? ts("audioTrack.unmute") : ts("audioTrack.mute")}+ </button>+ <button+ type="button"+ className={styles.secondaryBtn}+ onClick={() => void tl.removeAudioTrack(track.id)}+ >+ <Trash2 size={14} />+ {ts("audioTrack.remove")}+ </button>+ </Pane>+ );+}+// ─── Cursor ───────────────────────────────────────────────────────function safeAssetUrl(relativePath: string): string {diff --git a/src/components/ai-edition/v4/EditorShellV4.module.css b/src/components/ai-edition/v4/EditorShellV4.module.cssindex 1e313e34c..2096aa159 100644--- a/src/components/ai-edition/v4/EditorShellV4.module.css+++ b/src/components/ai-edition/v4/EditorShellV4.module.css@@ -1496,6 +1496,36 @@border-color: #a855f7;background: rgba(168, 85, 247, 0.14);}+/* Imported audio tracks (issue #350). A distinct teal so a BGM/voiceover track+ reads apart from the effect pills, and taller than a lane pill so the waveform+ inside it is legible. */+.laneAudio {+ border-color: #14b8a6;+ background: rgba(20, 184, 166, 0.16);+ height: 30px;+ top: 1px;+ cursor: pointer;+}+.laneAudio:active {+ cursor: pointer;+}+.laneAudioMuted {+ opacity: 0.5;+}+/* The label rides above the waveform (which is inset:0 behind it). */+.laneAudioLabel {+ position: relative;+ z-index: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ display: inline-flex;+ align-items: center;+ gap: 5px;+}+/* The audio lane is taller than the effect lanes to give the waveform room. */+.tlLaneAudio {+ height: 32px;+}.tlClips {position: relative;/* NOT a flex row. Clips are absolutely positioned by percentage of thediff --git a/src/components/ai-edition/v4/FloatingInspector.tsx b/src/components/ai-edition/v4/FloatingInspector.tsxindex ac162d322..c39495ca6 100644--- a/src/components/ai-edition/v4/FloatingInspector.tsx+++ b/src/components/ai-edition/v4/FloatingInspector.tsx@@ -43,6 +43,7 @@ import { CaptionsPane } from "../CaptionsPane";import { ColorField } from "../ColorField";import {AudioPane,+ AudioTrackPane,CursorPane,LayoutPane,SliderCell,@@ -113,13 +114,18 @@ export function FloatingInspector({return () => document.removeEventListener("mousedown", onDocMouseDown);}, [clipPickerOpen]);const selection = tl.selection;- const effectiveOpen = open || selection !== null;+ // An imported audio track is selected (issue #350) — like a region selection it+ // takes over the inspector body with its own pane (see AudioTrackPane).+ const audioTrackSelected = tl.selectedAudioTrackId !== null;+ const effectiveOpen = open || selection !== null || audioTrackSelected;return (<div className={styles.inspectorWrap}>{effectiveOpen ? (<div className={styles.inspector}>{selection ? (<SelectionPane tl={tl} onClose={() => tl.clearSelection()} />+ ) : audioTrackSelected ? (+ <AudioTrackPane tl={tl} />) : (<FacetBody facet={facet} onCollapse={onToggleOpen} transcriptProps={transcriptProps} />)}@@ -132,11 +138,11 @@ export function FloatingInspector({type="button"title={ts(labelKey)}aria-label={ts(labelKey)}- aria-pressed={!selection && open && facet === id}+ aria-pressed={!selection && !audioTrackSelected && open && facet === id}onClick={() => {// Switching facets while an element is selected should show// the facet, not leave the selection pane on top of it.- if (selection) tl.clearSelection();+ if (selection || audioTrackSelected) tl.clearSelection();if (facet === id && open) {onToggleOpen();} else {diff --git a/src/components/ai-edition/v4/V4Timeline.geometry.test.tsx b/src/components/ai-edition/v4/V4Timeline.geometry.test.tsxindex 8e515568c..91994d3a4 100644--- a/src/components/ai-edition/v4/V4Timeline.geometry.test.tsx+++ b/src/components/ai-edition/v4/V4Timeline.geometry.test.tsx@@ -84,6 +84,9 @@ function renderTimeline(selection: null,multiSelection: [],clipSelection: null,+ audioTracks: [],+ selectedAudioTrackId: null,+ selectAudioTrack: vi.fn(),clearSelection: vi.fn(),selectRegion: vi.fn(),selectClip: vi.fn(),diff --git a/src/components/ai-edition/v4/V4Timeline.tsx b/src/components/ai-edition/v4/V4Timeline.tsxindex f6c94e2ca..e8164e287 100644--- a/src/components/ai-edition/v4/V4Timeline.tsx+++ b/src/components/ai-edition/v4/V4Timeline.tsx@@ -4,11 +4,13 @@ import {Loader2,Maximize2,MessageSquare,+ Music,Pencil,Scissors,Sparkles,SplitSquareHorizontal,Trash2,+ VolumeX,Wand2,ZoomIn,} from "lucide-react";@@ -23,13 +25,13 @@ import {} from "react";import { toast } from "sonner";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";-import { fromFileUrl } from "@/components/video-editor/projectPersistence";+import { fromFileUrl, toFileUrl } from "@/components/video-editor/projectPersistence";import { ZOOM_DEPTH_SCALES } from "@/components/video-editor/types";import { useScopedT } from "@/contexts/I18nContext";import { useAudioPeaks } from "@/hooks/useAudioPeaks";import { createId } from "@/lib/ai-edition/document/ids";import { setUiProbeScrubbing } from "@/lib/ai-edition/perf/uiFrameProbe";-import type { AxcutClip } from "@/lib/ai-edition/schema";+import type { AxcutAudioTrack, AxcutClip } from "@/lib/ai-edition/schema";import { audioGainScalar } from "@/lib/ai-edition/store/editorSettings";import { useProjectStore } from "@/lib/ai-edition/store/projectStore";import { useTimelineTranscriptGate } from "@/lib/ai-edition/store/transcriptionStore";@@ -335,6 +337,70 @@ const ClipWaveform = memo(function ClipWaveform({);});+// One imported audio track on its lane (issue #350). Read-only for now — click to+// select; drag-to-move and edge-trim land in a follow-up. The waveform reuses+// ClipWaveform (its `.tlWave` is inset:0, so it paints behind the label here just+// as it does inside a clip), windowed to the track's trim and scaled by the+// track's own gain. `leftPct`/`widthPct` are precomputed by the parent so this+// stays memoisable — a doc edit that doesn't touch this track won't re-render it.+const AudioLanePill = memo(function AudioLanePill({+ track,+ url,+ assetDurationSec,+ leftPct,+ widthPct,+ selected,+ onSelect,+ label,+}: {+ track: AxcutAudioTrack;+ url: string | undefined;+ assetDurationSec: number | undefined;+ leftPct: number;+ widthPct: number;+ selected: boolean;+ onSelect: (id: string) => void;+ label: string;+}) {+ const duration = assetDurationSec ?? track.durationSec;+ return (+ <div+ role="button"+ tabIndex={0}+ className={`${styles.lanePill} ${styles.laneAudio}${+ selected ? ` ${styles.lanePillSel}` : ""+ }${track.mute ? ` ${styles.laneAudioMuted}` : ""}`}+ style={{ left: `${leftPct}%`, width: `${widthPct}%`, minWidth: 3 }}+ // Stop the pointer from starting a timeline scrub on .tlTracks; the click+ // below does the selecting.+ onPointerDown={(e) => e.stopPropagation()}+ onClick={(e) => {+ e.stopPropagation();+ onSelect(track.id);+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault();+ onSelect(track.id);+ }+ }}+ title={label}+ >+ <ClipWaveform+ videoUrl={url}+ assetDurationSec={duration}+ sourceStartSec={track.trimStartSec}+ sourceEndSec={track.trimEndSec ?? duration}+ gain={audioGainScalar(track.gainDb)}+ />+ <span className={styles.laneAudioLabel}>+ {track.mute ? <VolumeX size={11} /> : <Music size={11} />}+ {label}+ </span>+ </div>+ );+});+interface LanePill {id: string;kind: "annotation" | "speed" | "trim" | "zoom" | "cameraFullscreen";@@ -1482,6 +1548,34 @@ export function V4Timeline({hasAnyCamera ? t("hints.pressCameraFullscreen") : ts("layout.noWebcam"),)}</div>+ {/* Imported audio tracks (issue #350). Only shown once a track exists —+ audio arrives via the media panel's "Import audio", not a keystroke,+ so an empty lane would advertise nothing. */}+ {tl.audioTracks.length > 0 ? (+ <div className={`${styles.tlLane} ${styles.tlLaneAudio}`}>+ {tl.audioTracks.map((track) => {+ const asset = tl.assets.find((a) => a.id === track.assetId);+ const duration = asset?.durationSec ?? track.durationSec;+ const widthSec = Math.max(+ 0,+ (track.trimEndSec ?? duration) - track.trimStartSec,+ );+ return (+ <AudioLanePill+ key={track.id}+ track={track}+ url={asset ? toFileUrl(asset.originalPath) : undefined}+ assetDurationSec={duration}+ leftPct={pctOf(track.timelineStartSec)}+ widthPct={pctOf(widthSec)}+ selected={tl.selectedAudioTrackId === track.id}+ onSelect={tl.selectAudioTrack}+ label={track.label || asset?.label || ts("audioTrack.defaultLabel")}+ />+ );+ })}+ </div>+ ) : null}</>) : null}diff --git a/src/components/ai-edition/v4/V4Timeline.waveform.test.tsx b/src/components/ai-edition/v4/V4Timeline.waveform.test.tsxindex b5b2d9949..5234cd225 100644--- a/src/components/ai-edition/v4/V4Timeline.waveform.test.tsx+++ b/src/components/ai-edition/v4/V4Timeline.waveform.test.tsx@@ -115,6 +115,9 @@ function renderBars(atGainDb: number): string[] {selection: null,multiSelection: [],clipSelection: null,+ audioTracks: [],+ selectedAudioTrackId: null,+ selectAudioTrack: vi.fn(),clearSelection: vi.fn(),selectRegion: vi.fn(),selectClip: vi.fn(),diff --git a/src/i18n/locales/ar/editor.json b/src/i18n/locales/ar/editor.jsonindex 04bd4eba8..1977556d5 100644--- a/src/i18n/locales/ar/editor.json+++ b/src/i18n/locales/ar/editor.json@@ -154,7 +154,9 @@"detectedLanguage": "اللغة المكتشفة: {{language}}","noAudioTrack": "لا يوجد مسار صوتي","noAudioTrackHint": "لا يحتوي هذا الملف على مسار صوتي — لا يوجد ما يمكن نسخه.",- "noSpeechDetected": "لم يتم اكتشاف كلام"+ "noSpeechDetected": "لم يتم اكتشاف كلام",+ "couldNotAddAudio": "Could not add audio",+ "importAudio": "Import audio"},"exportDialog": {"title": "تصدير",diff --git a/src/i18n/locales/ar/settings.json b/src/i18n/locales/ar/settings.jsonindex f1e65ba1c..e4771f9ec 100644--- a/src/i18n/locales/ar/settings.json+++ b/src/i18n/locales/ar/settings.json@@ -326,5 +326,14 @@"outputGain": "ضبط مستوى الإخراج","reset": "إعادة ضبط الصوت","help": "اضبط مستوى إخراج الصوت. يُطبَّق بالطريقة نفسها في المعاينة وعند التصدير."+ },+ "audioTrack": {+ "defaultLabel": "Audio track",+ "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",+ "volume": "Volume",+ "offset": "Start (s)",+ "mute": "Mute",+ "unmute": "Unmute",+ "remove": "Remove track"}}diff --git a/src/i18n/locales/en/editor.json b/src/i18n/locales/en/editor.jsonindex e1692652d..4f539e0ac 100644--- a/src/i18n/locales/en/editor.json+++ b/src/i18n/locales/en/editor.json@@ -128,10 +128,12 @@"mediaStage": {"openProjectFirst": "Open a project first","couldNotAddAsset": "Could not add asset",+ "couldNotAddAudio": "Could not add audio","searchPlaceholder": "Search media…","dragHint": "Drag a clip onto the timeline below to add it","emptyHint": "No media yet — import a recording to get started.","importMedia": "Import media",+ "importAudio": "Import audio","added": "Added {{label}}","addToTimeline": "Add to timeline","addedToTimeline": "Added {{label}} to the timeline",diff --git a/src/i18n/locales/en/settings.json b/src/i18n/locales/en/settings.jsonindex 845f7e7fe..3b555d74e 100644--- a/src/i18n/locales/en/settings.json+++ b/src/i18n/locales/en/settings.json@@ -79,6 +79,15 @@"outputGain": "Output level","reset": "Reset audio"},+ "audioTrack": {+ "defaultLabel": "Audio track",+ "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",+ "volume": "Volume",+ "offset": "Start (s)",+ "mute": "Mute",+ "unmute": "Unmute",+ "remove": "Remove track"+ },"effects": {"title": "Composition","blurBg": "Blur BG",diff --git a/src/i18n/locales/es/editor.json b/src/i18n/locales/es/editor.jsonindex 46f0d3eaf..a384c6436 100644--- a/src/i18n/locales/es/editor.json+++ b/src/i18n/locales/es/editor.json@@ -154,7 +154,9 @@"detectedLanguage": "Idioma detectado: {{language}}","noAudioTrack": "Sin pista de audio","noAudioTrackHint": "Este medio no tiene pista de audio: no hay nada que transcribir.",- "noSpeechDetected": "No se detectó voz"+ "noSpeechDetected": "No se detectó voz",+ "couldNotAddAudio": "Could not add audio",+ "importAudio": "Import audio"},"exportDialog": {"title": "Exportar",diff --git a/src/i18n/locales/es/settings.json b/src/i18n/locales/es/settings.jsonindex 56976bcfc..88983d170 100644--- a/src/i18n/locales/es/settings.json+++ b/src/i18n/locales/es/settings.json@@ -326,5 +326,14 @@"outputGain": "Ajuste de salida","reset": "Restablecer audio","help": "Ajusta el nivel de salida del audio. Se aplica igual en la vista previa y en la exportación."+ },+ "audioTrack": {+ "defaultLabel": "Audio track",+ "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",+ "volume": "Volume",+ "offset": "Start (s)",+ "mute": "Mute",+ "unmute": "Unmute",+ "remove": "Remove track"}}diff --git a/src/i18n/locales/fr/editor.json b/src/i18n/locales/fr/editor.jsonindex 3eb0dfa4e..0dce49bc6 100644--- a/src/i18n/locales/fr/editor.json+++ b/src/i18n/locales/fr/editor.json@@ -154,7 +154,9 @@"detectedLanguage": "Langue détectée : {{language}}","noAudioTrack": "Aucune piste audio","noAudioTrackHint": "Ce média n'a pas de piste audio — il n'y a rien à transcrire.",- "noSpeechDetected": "Aucune parole détectée"+ "noSpeechDetected": "Aucune parole détectée",+ "couldNotAddAudio": "Could not add audio",+ "importAudio": "Import audio"},"exportDialog": {"title": "Exporter",diff --git a/src/i18n/locales/fr/settings.json b/src/i18n/locales/fr/settings.jsonindex 70c7f4b35..771393441 100644--- a/src/i18n/locales/fr/settings.json+++ b/src/i18n/locales/fr/settings.json@@ -326,5 +326,14 @@"outputGain": "Niveau de sortie","reset": "Réinitialiser l’audio","help": "Ajustez le niveau de sortie audio. Il s’applique à l’identique dans l’aperçu et à l’export."+ },+ "audioTrack": {+ "defaultLabel": "Audio track",+ "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",+ "volume": "Volume",+ "offset": "Start (s)",+ "mute": "Mute",+ "unmute": "Unmute",+ "remove": "Remove track"}}diff --git a/src/i18n/locales/it/editor.json b/src/i18n/locales/it/editor.jsonindex 214b0d10a..254b464a5 100644--- a/src/i18n/locales/it/editor.json+++ b/src/i18n/locales/it/editor.json@@ -154,7 +154,9 @@"detectedLanguage": "Lingua rilevata: {{language}}","noAudioTrack": "Nessuna traccia audio","noAudioTrackHint": "Questo contenuto non ha una traccia audio: non c'è nulla da trascrivere.",- "noSpeechDetected": "Nessun parlato rilevato"+ "noSpeechDetected": "Nessun parlato rilevato",+ "couldNotAddAudio": "Could not add audio",+ "importAudio": "Import audio"},"exportDialog": {"title": "Esporta",diff --git a/src/i18n/locales/it/settings.json b/src/i18n/locales/it/settings.jsonindex 41b398039..85b8313bb 100644--- a/src/i18n/locales/it/settings.json+++ b/src/i18n/locales/it/settings.json@@ -326,5 +326,14 @@"outputGain": "Livello di uscita","reset": "Reimposta audio","help": "Regola il livello di uscita audio. Si applica allo stesso modo nell’anteprima e nell’esportazione."+ },+ "audioTrack": {+ "defaultLabel": "Audio track",+ "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",+ "volume": "Volume",+ "offset": "Start (s)",+ "mute": "Mute",+ "unmute": "Unmute",+ "remove": "Remove track"}}diff --git a/src/i18n/locales/ja-JP/editor.json b/src/i18n/locales/ja-JP/editor.jsonindex e12096ed1..42cbbbc1d 100644--- a/src/i18n/locales/ja-JP/editor.json+++ b/src/i18n/locales/ja-JP/editor.json@@ -154,7 +154,9 @@"detectedLanguage": "検出された言語: {{language}}","noAudioTrack": "音声トラックがありません","noAudioTrackHint": "このメディアには音声トラックがないため、文字起こしできません。",- "noSpeechDetected": "音声が検出されませんでした"+ "noSpeechDetected": "音声が検出されませんでした",+ "couldNotAddAudio": "Could not add audio",+ "importAudio": "Import audio"},"exportDialog": {"title": "エクスポート",diff --git a/src/i18n/locales/ja-JP/settings.json b/src/i18n/locales/ja-JP/settings.jsonindex a908e0550..7bcfefc30 100644--- a/src/i18n/locales/ja-JP/settings.json+++ b/src/i18n/locales/ja-JP/settings.json@@ -326,5 +326,14 @@"outputGain": "出力レベル","reset": "オーディオをリセット","help": "音声の出力レベルを調整します。プレビューと書き出しで同じように適用されます。"+ },+ "audioTrack": {+ "defaultLabel": "Audio track",+ "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",+ "volume": "Volume",+ "offset": "Start (s)",+ "mute": "Mute",+ "unmute": "Unmute",+ "remove": "Remove track"}}diff --git a/src/i18n/locales/ko-KR/editor.json b/src/i18n/locales/ko-KR/editor.jsonindex a1fc34a62..cfcf21069 100644--- a/src/i18n/locales/ko-KR/editor.json+++ b/src/i18n/locales/ko-KR/editor.json@@ -154,7 +154,9 @@"detectedLanguage": "감지된 언어: {{language}}","noAudioTrack": "오디오 트랙 없음","noAudioTrackHint": "이 미디어에는 오디오 트랙이 없어 받아쓸 내용이 없습니다.",- "noSpeechDetected": "음성이 감지되지 않음"+ "noSpeechDetected": "음성이 감지되지 않음",+ "couldNotAddAudio": "Could not add audio",+ "importAudio": "Import audio"},"exportDialog": {"title": "내보내기",diff --git a/src/i18n/locales/ko-KR/settings.json b/src/i18n/locales/ko-KR/settings.jsonindex 3bf3e59a7..3d3f36c49 100644--- a/src/i18n/locales/ko-KR/settings.json+++ b/src/i18n/locales/ko-KR/settings.json@@ -326,5 +326,14 @@"outputGain": "출력 레벨","reset": "오디오 재설정","help": "오디오 출력 레벨을 조정합니다. 미리보기와 내보내기에 동일하게 적용됩니다."+ },+ "audioTrack": {+ "defaultLabel": "Audio track",+ "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",+ "volume": "Volume",+ "offset": "Start (s)",+ "mute": "Mute",+ "unmute": "Unmute",+ "remove": "Remove track"}}diff --git a/src/i18n/locales/pt-BR/editor.json b/src/i18n/locales/pt-BR/editor.jsonindex 799f3be74..ef6b22382 100644--- a/src/i18n/locales/pt-BR/editor.json+++ b/src/i18n/locales/pt-BR/editor.json@@ -154,7 +154,9 @@"detectedLanguage": "Idioma detectado: {{language}}","noAudioTrack": "Sem faixa de áudio","noAudioTrackHint": "Esta mídia não tem faixa de áudio — não há nada para transcrever.",- "noSpeechDetected": "Nenhuma fala detectada"+ "noSpeechDetected": "Nenhuma fala detectada",+ "couldNotAddAudio": "Could not add audio",+ "importAudio": "Import audio"},"exportDialog": {"title": "Exportar",diff --git a/src/i18n/locales/pt-BR/settings.json b/src/i18n/locales/pt-BR/settings.jsonindex 1218d1f85..bef4eed8d 100644--- a/src/i18n/locales/pt-BR/settings.json+++ b/src/i18n/locales/pt-BR/settings.json@@ -326,5 +326,14 @@"outputGain": "Nível de saída","reset": "Redefinir áudio","help": "Ajuste o nível de saída do áudio. Ele se aplica da mesma forma na prévia e na exportação."+ },+ "audioTrack": {+ "defaultLabel": "Audio track",+ "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",+ "volume": "Volume",+ "offset": "Start (s)",+ "mute": "Mute",+ "unmute": "Unmute",+ "remove": "Remove track"}}diff --git a/src/i18n/locales/ru/editor.json b/src/i18n/locales/ru/editor.jsonindex db5216291..0956a0cf8 100644--- a/src/i18n/locales/ru/editor.json+++ b/src/i18n/locales/ru/editor.json@@ -154,7 +154,9 @@"detectedLanguage": "Обнаруженный язык: {{language}}","noAudioTrack": "Нет аудиодорожки","noAudioTrackHint": "В этом медиафайле нет аудиодорожки — расшифровывать нечего.",- "noSpeechDetected": "Речь не обнаружена"+ "noSpeechDetected": "Речь не обнаружена",+ "couldNotAddAudio": "Could not add audio",+ "importAudio": "Import audio"},"exportDialog": {"title": "Экспорт",diff --git a/src/i18n/locales/ru/settings.json b/src/i18n/locales/ru/settings.jsonindex 5b235bf76..505d32dc9 100644--- a/src/i18n/locales/ru/settings.json+++ b/src/i18n/locales/ru/settings.json@@ -326,5 +326,14 @@"outputGain": "Уровень выхода","reset": "Сбросить аудио","help": "Настройте уровень звука на выходе. Он одинаково применяется в предпросмотре и при экспорте."+ },+ "audioTrack": {+ "defaultLabel": "Audio track",+ "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",+ "volume": "Volume",+ "offset": "Start (s)",+ "mute": "Mute",+ "unmute": "Unmute",+ "remove": "Remove track"}}diff --git a/src/i18n/locales/tr/editor.json b/src/i18n/locales/tr/editor.jsonindex 5b8e9922b..c66cac894 100644--- a/src/i18n/locales/tr/editor.json+++ b/src/i18n/locales/tr/editor.json@@ -154,7 +154,9 @@"detectedLanguage": "Algılanan dil: {{language}}","noAudioTrack": "Ses parçası yok","noAudioTrackHint": "Bu medyada ses parçası yok — metne dökülecek bir şey bulunmuyor.",- "noSpeechDetected": "Konuşma algılanmadı"+ "noSpeechDetected": "Konuşma algılanmadı",+ "couldNotAddAudio": "Could not add audio",+ "importAudio": "Import audio"},"exportDialog": {"title": "Dışa Aktar",diff --git a/src/i18n/locales/tr/settings.json b/src/i18n/locales/tr/settings.jsonindex 05ec9bf03..add958d0f 100644--- a/src/i18n/locales/tr/settings.json+++ b/src/i18n/locales/tr/settings.json@@ -326,5 +326,14 @@"outputGain": "Çıkış seviyesi","reset": "Sesi sıfırla","help": "Ses çıkış seviyesini ayarlayın. Önizlemede ve dışa aktarmada aynı şekilde uygulanır."+ },+ "audioTrack": {+ "defaultLabel": "Audio track",+ "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",+ "volume": "Volume",+ "offset": "Start (s)",+ "mute": "Mute",+ "unmute": "Unmute",+ "remove": "Remove track"}}diff --git a/src/i18n/locales/vi/editor.json b/src/i18n/locales/vi/editor.jsonindex 821875edb..f668c006a 100644--- a/src/i18n/locales/vi/editor.json+++ b/src/i18n/locales/vi/editor.json@@ -154,7 +154,9 @@"detectedLanguage": "Ngôn ngữ phát hiện: {{language}}","noAudioTrack": "Không có bản âm thanh","noAudioTrackHint": "Media này không có bản âm thanh — không có gì để phiên âm.",- "noSpeechDetected": "Không phát hiện giọng nói"+ "noSpeechDetected": "Không phát hiện giọng nói",+ "couldNotAddAudio": "Could not add audio",+ "importAudio": "Import audio"},"exportDialog": {"title": "Xuất",diff --git a/src/i18n/locales/vi/settings.json b/src/i18n/locales/vi/settings.jsonindex 586d7f7b1..e2d3b31db 100644--- a/src/i18n/locales/vi/settings.json+++ b/src/i18n/locales/vi/settings.json@@ -326,5 +326,14 @@"outputGain": "Mức đầu ra","reset": "Đặt lại âm thanh","help": "Điều chỉnh mức đầu ra của âm thanh. Nó được áp dụng giống hệt nhau trong bản xem trước và khi xuất."+ },+ "audioTrack": {+ "defaultLabel": "Audio track",+ "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",+ "volume": "Volume",+ "offset": "Start (s)",+ "mute": "Mute",+ "unmute": "Unmute",+ "remove": "Remove track"}}diff --git a/src/i18n/locales/zh-CN/editor.json b/src/i18n/locales/zh-CN/editor.jsonindex 7723d101d..73bead3f5 100644--- a/src/i18n/locales/zh-CN/editor.json+++ b/src/i18n/locales/zh-CN/editor.json@@ -154,7 +154,9 @@"detectedLanguage": "检测到的语言:{{language}}","noAudioTrack": "无音频轨道","noAudioTrackHint": "此媒体没有音频轨道,没有可转录的内容。",- "noSpeechDetected": "未检测到语音"+ "noSpeechDetected": "未检测到语音",+ "couldNotAddAudio": "Could not add audio",+ "importAudio": "Import audio"},"exportDialog": {"title": "导出",diff --git a/src/i18n/locales/zh-CN/settings.json b/src/i18n/locales/zh-CN/settings.jsonindex fafb66f7e..e5091364f 100644--- a/src/i18n/locales/zh-CN/settings.json+++ b/src/i18n/locales/zh-CN/settings.json@@ -326,5 +326,14 @@"outputGain": "输出电平","reset": "重置音频","help": "调整音频输出电平。它在预览和导出中的效果完全一致。"+ },+ "audioTrack": {+ "defaultLabel": "Audio track",+ "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",+ "volume": "Volume",+ "offset": "Start (s)",+ "mute": "Mute",+ "unmute": "Unmute",+ "remove": "Remove track"}}diff --git a/src/i18n/locales/zh-TW/editor.json b/src/i18n/locales/zh-TW/editor.jsonindex 3edf5f320..58785ad3a 100644--- a/src/i18n/locales/zh-TW/editor.json+++ b/src/i18n/locales/zh-TW/editor.json@@ -154,7 +154,9 @@"detectedLanguage": "偵測到的語言:{{language}}","noAudioTrack": "無音訊軌道","noAudioTrackHint": "此媒體沒有音訊軌道,沒有可轉錄的內容。",- "noSpeechDetected": "未偵測到語音"+ "noSpeechDetected": "未偵測到語音",+ "couldNotAddAudio": "Could not add audio",+ "importAudio": "Import audio"},"exportDialog": {"title": "匯出",diff --git a/src/i18n/locales/zh-TW/settings.json b/src/i18n/locales/zh-TW/settings.jsonindex f09730292..4a4499973 100644--- a/src/i18n/locales/zh-TW/settings.json+++ b/src/i18n/locales/zh-TW/settings.json@@ -327,5 +327,14 @@"outputGain": "輸出音量","reset": "重設音訊","help": "調整音訊輸出電平。它在預覽與匯出中的效果完全一致。"+ },+ "audioTrack": {+ "defaultLabel": "Audio track",+ "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",+ "volume": "Volume",+ "offset": "Start (s)",+ "mute": "Mute",+ "unmute": "Unmute",+ "remove": "Remove track"}}diff --git a/src/lib/ai-edition/store/documentWriteAudit.test.ts b/src/lib/ai-edition/store/documentWriteAudit.test.tsindex 6a76e8013..eacf97b97 100644--- a/src/lib/ai-edition/store/documentWriteAudit.test.ts+++ b/src/lib/ai-edition/store/documentWriteAudit.test.ts@@ -168,6 +168,12 @@ const DECLARED: WritePath[] = [// Linking the camera track found next to a newly added asset. Part of the// import, not an edit of its own.w("src/lib/ai-edition/store/projectStore.ts", "addAsset", "save", "automatic"),+ // Folding an imported audio file's probed duration onto its asset (issue #350).+ // Part of the import, like the camera link above — not an edit of its own.+ w("src/lib/ai-edition/store/projectStore.ts", "addAudioAsset", "save", "automatic"),+ // Placing an imported audio track on the timeline. The user asked for it, via the+ // media panel's "Import audio" or the timeline.+ w("src/lib/ai-edition/store/projectStore.ts", "addAudioTrack", "save", "gesture"),// THE round-3 fix. This is the shape that defeated round 2: a store action that// writes on someone else's behalf. It forwards now, so its callers decide.w("src/lib/ai-edition/store/projectStore.ts", "replaceTimeline", "save", "forwarded"),@@ -234,6 +240,13 @@ const DECLARED: WritePath[] = [w("src/lib/ai-edition/store/useTimeline.ts", "duplicateClip", "save", "gesture"),w("src/lib/ai-edition/store/useTimeline.ts", "insertClipAt", "save", "gesture"),w("src/lib/ai-edition/store/useTimeline.ts", "moveClip", "save", "gesture"),+ // Imported audio tracks (issue #350). Each is a direct user edit — drag/trim the+ // track, change its level, mute it, or delete it — one undo step apiece.+ w("src/lib/ai-edition/store/useTimeline.ts", "moveAudioTrack", "save", "gesture"),+ w("src/lib/ai-edition/store/useTimeline.ts", "removeAudioTrack", "save", "gesture"),+ w("src/lib/ai-edition/store/useTimeline.ts", "resizeAudioTrack", "save", "gesture"),+ w("src/lib/ai-edition/store/useTimeline.ts", "setAudioTrackGain", "save", "gesture"),+ w("src/lib/ai-edition/store/useTimeline.ts", "toggleAudioTrackMute", "save", "gesture"),// The round-2 defect: a background duration probe every freshly imported asset// fires, because `addAsset` never populates `durationSec`.w("src/lib/ai-edition/store/useTimeline.ts", "probeAndCorrectClip", "save", "automatic"),diff --git a/src/lib/ai-edition/store/projectStore.test.ts b/src/lib/ai-edition/store/projectStore.test.tsindex 0c920be7a..e2f69fce7 100644--- a/src/lib/ai-edition/store/projectStore.test.ts+++ b/src/lib/ai-edition/store/projectStore.test.ts@@ -374,6 +374,84 @@ describe("useProjectStore", () => {expect(useProjectStore.getState().document?.assets[0]?.durationSec).toBe(8.25);});+ // Placement + selection for imported audio tracks (issue #350).+ const audioAsset = {+ id: "audio_1",+ kind: "audio" as const,+ label: "voiceover.mp3",+ originalPath: "/tmp/vo.mp3",+ durationSec: 12,+ cameraTrack: null,+ };++ it("addAudioTrack places a track at the playhead for an audio asset and selects it", async () => {+ useProjectStore.setState({+ projectId: "proj_test",+ document: { ...sampleDoc, assets: [audioAsset] },+ revision: 1,+ status: "ready",+ error: null,+ currentTimeSec: 5,+ });+ bridgeMocks.save.mockImplementation((document: unknown) =>+ Promise.resolve({ success: true, document }),+ );++ const id = await useProjectStore.getState().addAudioTrack("audio_1");++ const tracks = useProjectStore.getState().document?.audioTracks ?? [];+ expect(tracks).toHaveLength(1);+ expect(tracks[0]).toMatchObject({ assetId: "audio_1", timelineStartSec: 5, durationSec: 12 });+ expect(id).toBe(tracks[0]?.id);+ // Placing a track selects it so the inspector opens on its controls.+ expect(useProjectStore.getState().selectedAudioTrackId).toBe(id);+ });++ it("addAudioTrack refuses a non-audio (or unknown) asset and selects nothing", async () => {+ useProjectStore.setState({+ projectId: "proj_test",+ document: sampleDoc, // its only asset, if any, is not audio+ revision: 1,+ status: "ready",+ error: null,+ });+ expect(await useProjectStore.getState().addAudioTrack("nope")).toBeNull();+ expect(useProjectStore.getState().selectedAudioTrackId).toBeNull();+ });++ it("importAudioAsset adds the asset then places and selects a track in one action", async () => {+ useProjectStore.setState({+ projectId: "proj_test",+ document: sampleDoc,+ revision: 1,+ status: "ready",+ error: null,+ currentTimeSec: 0,+ });+ durationMocks.probeAudioDuration.mockResolvedValue(12);+ bridgeMocks.addAsset.mockResolvedValue({+ assetId: "audio_1",+ document: { ...sampleDoc, assets: [audioAsset] },+ });+ bridgeMocks.save.mockImplementation((document: unknown) =>+ Promise.resolve({ success: true, document }),+ );++ const asset = await useProjectStore.getState().importAudioAsset("/tmp/vo.mp3");++ expect(asset?.id).toBe("audio_1");+ const tracks = useProjectStore.getState().document?.audioTracks ?? [];+ expect(tracks).toHaveLength(1);+ expect(tracks[0]?.assetId).toBe("audio_1");+ expect(useProjectStore.getState().selectedAudioTrackId).toBe(tracks[0]?.id);+ });++ it("clear() resets the audio-track selection", () => {+ useProjectStore.setState({ selectedAudioTrackId: "audio_x" });+ useProjectStore.getState().clear();+ expect(useProjectStore.getState().selectedAudioTrackId).toBeNull();+ });+// The save boundary. Every write in the app funnels through `saveDocument`, and// almost every caller `void`s it from a click handler, so what this function does// with a failure IS what the user sees.diff --git a/src/lib/ai-edition/store/projectStore.ts b/src/lib/ai-edition/store/projectStore.tsindex 4d2eeb30c..fef92136e 100644--- a/src/lib/ai-edition/store/projectStore.ts+++ b/src/lib/ai-edition/store/projectStore.ts@@ -3,8 +3,9 @@ import { create } from "zustand";import { toFileUrl } from "@/components/video-editor/projectPersistence";import { toastText } from "@/i18n/toastText";import { nativeBridgeClient } from "@/native/client";+import { appendAudioTrack } from "../document/audioTracks";import { type Interval, replaceTimeline as replaceTimelineOp } from "../document/timeline";-import { type AxcutAsset, type AxcutDocument, documentSchema } from "../schema";+import { type AxcutAsset, type AxcutDocument, createAudioTrack, documentSchema } from "../schema";import { probeAudioDuration, probeVideoDimensions } from "../timeline/duration";import { clearHistory, currentWriteEpoch, pushHistory } from "./undoStack";@@ -58,6 +59,11 @@ export interface ProjectState {error: string | null;sourceDurationSec: number;currentTimeSec: number;+ /** The selected imported audio track (issue #350), or null. In the store — not+ * `useTimeline`'s local selection — because the media panel (which imports the+ * file) and the inspector (which edits it) sit in different component subtrees+ * and both need to read/set it; the region/clip selection stays hook-local. */+ selectedAudioTrackId: string | null;/** Single source of truth for "is the timeline transport playing?" — previously* duplicated as separate local state in NewEditorShell AND VirtualPreview, each* independently wired to the same raw <video> DOM events, which let one advance@@ -80,6 +86,18 @@ export interface ProjectState {* asset, or null if the write was superseded.*/addAudioAsset: (path: string, label?: string) => Promise<AxcutAsset | null>;+ /**+ * One-shot "Import audio" for the media panel (issue #350): {@link addAudioAsset}+ * then place a track for it at the current playhead and select it, so the file+ * lands visibly on the timeline in a single user action. Returns the asset (or+ * null if the import was superseded). The timeline's own {@link addAudioTrack}+ * covers placing an already-imported asset.+ */+ importAudioAsset: (path: string, label?: string) => Promise<AxcutAsset | null>;+ /** Place a track for an already-imported audio asset at `timelineStartSec`+ * (default: the playhead) and select it. Returns the new track id, or null. */+ addAudioTrack: (assetId: string, timelineStartSec?: number) => Promise<string | null>;+ setSelectedAudioTrackId: (id: string | null) => void;removeAsset: (assetId: string) => Promise<void>;/*** Write the document to disk. Resolves `true` when it took effect, `false` when it@@ -167,6 +185,7 @@ export const useProjectStore = create<ProjectState>((set, get) => ({error: null,sourceDurationSec: 0,currentTimeSec: 0,+ selectedAudioTrackId: null,playing: false,dirty: false,lastSavedAt: null,@@ -187,6 +206,7 @@ export const useProjectStore = create<ProjectState>((set, get) => ({error: null,dirty: false,lastSavedAt: new Date(),+ selectedAudioTrackId: null,});clearHistory();} catch (error) {@@ -378,6 +398,39 @@ export const useProjectStore = create<ProjectState>((set, get) => ({return document.assets.find((a) => a.id === addedAsset.id) ?? addedAsset;},+ setSelectedAudioTrackId(id) {+ set({ selectedAudioTrackId: id });+ },++ async addAudioTrack(assetId, timelineStartSec) {+ const document = get().document;+ if (!document) return null;+ const asset = document.assets.find((a) => a.id === assetId);+ if (!asset || asset.kind !== "audio") return null;+ const track = createAudioTrack({+ assetId,+ durationSec: asset.durationSec ?? 0,+ // Default to the playhead (output-timeline seconds), matching the+ // timeline hook's placement.+ timelineStartSec: timelineStartSec ?? get().currentTimeSec,+ label: asset.label,+ });+ if (!(await get().saveDocument(appendAudioTrack(document, track), { history: true }))) {+ return null;+ }+ set({ selectedAudioTrackId: track.id });+ return track.id;+ },++ async importAudioAsset(path, label) {+ const asset = await get().addAudioAsset(path, label);+ if (!asset) return null;+ // addAudioAsset already committed the asset (with its probed duration), so+ // the current document is the one to place the track on.+ await get().addAudioTrack(asset.id);+ return asset;+ },+async removeAsset(assetId) {const { projectId } = get();if (!projectId) throw new Error("No project loaded");@@ -504,6 +557,7 @@ export const useProjectStore = create<ProjectState>((set, get) => ({error: null,sourceDurationSec: 0,currentTimeSec: 0,+ selectedAudioTrackId: null,playing: false,dirty: false,lastSavedAt: null,diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.tsindex 90524d9e1..f34779b59 100644--- a/src/lib/ai-edition/store/useTimeline.ts+++ b/src/lib/ai-edition/store/useTimeline.ts@@ -8,7 +8,6 @@ import { toFileUrl } from "@/components/video-editor/projectPersistence";import type { AnnotationRegion, AnnotationType } from "@/components/video-editor/types";import { useScopedT } from "@/contexts/I18nContext";import {- appendAudioTrack as appendAudioTrackInDocument,moveAudioTrack as moveAudioTrackInDocument,removeAudioTrack as removeAudioTrackInDocument,setAudioTrackGain as setAudioTrackGainInDocument,@@ -27,7 +26,7 @@ import {resequenceClips,setClipSourceRange,} from "../document/timeline";-import { type AxcutClipCropRegion, type AxcutDocument, createAudioTrack } from "../schema";+import type { AxcutClipCropRegion, AxcutDocument } from "../schema";import { hasAnyClipWithCamera } from "../timeline/camera";import { probeVideoDimensions, probeVideoDuration } from "../timeline/duration";import {@@ -113,6 +112,14 @@ export function useTimeline() {// the Delete key operates on.const [multiSelection, setMultiSelection] = useState<RegionHandle[]>([]);const [clipSelection, setClipSelection] = useState<string | null>(null);+ // The selected imported audio track (issue #350) lives in the project store —+ // not here — because the media panel and the inspector, in different subtrees,+ // both touch it (see projectStore). It shares "this is the thing I mean"+ // exclusivity with the region/clip selection above, so the selects below clear+ // it and it clears them, but it carries none of the region delete/anchor logic.+ const selectedAudioTrackId = useProjectStore((s) => s.selectedAudioTrackId);+ const setSelectedAudioTrackId = useProjectStore((s) => s.setSelectedAudioTrackId);+ const storeAddAudioTrack = useProjectStore((s) => s.addAudioTrack);// Pre-drag snapshots for the two optimistic paths (zoom focus, annotations), so a// failed commit can put the document back instead of leaving an edit on screen that// was never written.@@ -902,6 +909,7 @@ export function useTimeline() {(kind: RegionKind, id: string, opts?: { additive?: boolean }) => {const handle = { kind, id };setClipSelection(null);+ setSelectedAudioTrackId(null);if (opts?.additive) {// Shift-click toggles membership; the focused region follows the click.setMultiSelection((prev) => {@@ -914,14 +922,15 @@ export function useTimeline() {setMultiSelection([handle]);setSelection(handle);},- [],+ [setSelectedAudioTrackId],);const clearSelection = useCallback(() => {setSelection(null);setMultiSelection([]);setClipSelection(null);- }, []);+ setSelectedAudioTrackId(null);+ }, [setSelectedAudioTrackId]);// The Edit Clip dialog's Apply, as ONE document and ONE save.//@@ -1157,11 +1166,26 @@ export function useTimeline() {);// Mirror of selectRegion: picking a clip retires the pill selection.- const selectClip = useCallback((id: string) => {- setClipSelection(id);- setSelection(null);- setMultiSelection([]);- }, []);+ const selectClip = useCallback(+ (id: string) => {+ setClipSelection(id);+ setSelection(null);+ setMultiSelection([]);+ setSelectedAudioTrackId(null);+ },+ [setSelectedAudioTrackId],+ );++ // Picking an audio track retires every other selection, same exclusivity rule.+ const selectAudioTrack = useCallback(+ (id: string) => {+ setSelectedAudioTrackId(id);+ setSelection(null);+ setMultiSelection([]);+ setClipSelection(null);+ },+ [setSelectedAudioTrackId],+ );const speedRegions = hasDoc? (((document.legacyEditor as Record<string, unknown> | null)?.speedRegions as Array<{@@ -1186,33 +1210,21 @@ export function useTimeline() {// anchoring — each just writes `document.audioTracks` through the pure ops.// Place a new track for an imported audio asset, its head at the playhead (in- // output-timeline seconds) unless the caller says otherwise. Returns the new- // track's id so the UI can select it, or null if the write didn't take.+ // output-timeline seconds) unless the caller says otherwise. Delegates to the+ // store op, which also selects the new track and returns its id (or null).const addAudioTrack = useCallback(- async (assetId: string, timelineStartSec?: number): Promise<string | null> => {- if (!document) return null;- const asset = document.assets.find((a) => a.id === assetId);- if (!asset || asset.kind !== "audio") return null;- const track = createAudioTrack({- assetId,- durationSec: asset.durationSec ?? 0,- timelineStartSec: timelineStartSec ?? playheadSec(),- label: asset.label,- });- if (!(await saveDocument(appendAudioTrackInDocument(document, track), { history: true }))) {- return null;- }- return track.id;- },- [document, saveDocument],+ (assetId: string, timelineStartSec?: number): Promise<string | null> =>+ storeAddAudioTrack(assetId, timelineStartSec ?? playheadSec()),+ [storeAddAudioTrack],);const removeAudioTrack = useCallback(async (trackId: string) => {if (!document) return;+ if (selectedAudioTrackId === trackId) setSelectedAudioTrackId(null);await saveDocument(removeAudioTrackInDocument(document, trackId), { history: true });},- [document, saveDocument],+ [document, saveDocument, selectedAudioTrackId, setSelectedAudioTrackId],);// Drag-reposition the track's head. `timelineStartSec` is output-timeline time.@@ -1283,6 +1295,8 @@ export function useTimeline() {resizeAudioTrack,setAudioTrackGain,toggleAudioTrackMute,+ selectedAudioTrackId,+ selectAudioTrack,selectRegion,clearSelection,applyClipEdit,