Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

feat(editor): play imported audio tracks in the preview

Benjamin Freeman29beb9ff2aa8
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index b2c41aa31..791a08f1e 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -1244,6 +1244,11 @@ export function NewEditorShell() {
hasProject={hasProject}
hasAsset={hasAsset}
videoSources={videoSources}
+ // Imported audio tracks (issue #350). `videoSources` already
+ // resolves a URL for every asset (audio included), so it doubles as
+ // the audio source list; VirtualPreview looks each track up by assetId.
+ audioTracks={tl.audioTracks}
+ audioSources={videoSources}
clips={clips}
zoomRegions={tl.zoomRegions}
speedRegions={tl.speedRegions}
diff --git a/src/components/ai-edition/Preview.tsx b/src/components/ai-edition/Preview.tsx
index aaf04f2db..cd6868e75 100644
--- a/src/components/ai-edition/Preview.tsx
+++ b/src/components/ai-edition/Preview.tsx
@@ -3,6 +3,7 @@ import type { CameraFullscreenRegion, ZoomFocus } from "@/components/video-edito
import { useScopedT } from "@/contexts/I18nContext";
import type {
AxcutAnnotationRegion,
+ AxcutAudioTrack,
AxcutClip,
AxcutTrimRange,
AxcutZoomRegion,
@@ -21,6 +22,12 @@ interface PreviewProps {
hasProject: boolean;
hasAsset: boolean;
videoSources: VideoSource[];
+ /** Imported audio tracks and the (unfiltered) asset URLs they resolve to
+ * (issue #350). Passed straight through to VirtualPreview — unlike the video
+ * `previewSources` below, these are NOT narrowed to clip-referenced assets,
+ * since an audio track has no clip. */
+ audioTracks?: AxcutAudioTrack[];
+ audioSources?: VideoSource[];
clips: AxcutClip[];
zoomRegions?: AxcutZoomRegion[];
speedRegions?: SpeedRegion[];
@@ -52,6 +59,8 @@ export function Preview({
hasProject,
hasAsset,
videoSources,
+ audioTracks = [],
+ audioSources = [],
clips,
zoomRegions,
speedRegions,
@@ -178,6 +187,8 @@ export function Preview({
<>
<PreviewCanvas
videoSources={previewSources}
+ audioTracks={audioTracks}
+ audioSources={audioSources}
clips={clips}
zoomRegions={zoomRegions}
speedRegions={speedRegions}
diff --git a/src/components/ai-edition/PreviewCanvas.tsx b/src/components/ai-edition/PreviewCanvas.tsx
index 6f59e066f..150012b95 100644
--- a/src/components/ai-edition/PreviewCanvas.tsx
+++ b/src/components/ai-edition/PreviewCanvas.tsx
@@ -34,6 +34,7 @@ import { useScopedT } from "@/contexts/I18nContext";
import { resolveAspectRatioValue } from "@/lib/ai-edition/document/outputFormat";
import type {
AxcutAnnotationRegion,
+ AxcutAudioTrack,
AxcutClip,
AxcutTrimRange,
AxcutZoomRegion,
@@ -65,6 +66,10 @@ type BlurData = NonNullable<AxcutAnnotationRegion["blurData"]>;
interface PreviewCanvasProps {
videoSources: VideoSource[];
+ /** Imported audio tracks + their asset URLs (issue #350), forwarded to
+ * VirtualPreview. */
+ audioTracks?: AxcutAudioTrack[];
+ audioSources?: VideoSource[];
clips: AxcutClip[];
zoomRegions?: AxcutZoomRegion[];
speedRegions?: SpeedRegion[];
diff --git a/src/components/ai-edition/VirtualPreview.audio.test.ts b/src/components/ai-edition/VirtualPreview.audio.test.ts
index 208bf05a2..c8e38beff 100644
--- a/src/components/ai-edition/VirtualPreview.audio.test.ts
+++ b/src/components/ai-edition/VirtualPreview.audio.test.ts
@@ -1,8 +1,10 @@
import { describe, expect, it } from "vitest";
+import type { AxcutAudioTrack } from "@/lib/ai-edition/schema";
import {
applyPreviewAudioSettings,
type PreviewAudioGraph,
resolveAudioTrackPlayback,
+ resolveTimelineAudioPlayback,
} from "./VirtualPreview";
/** Minimal stand-in: the function only ever touches `gain.gain.value`. */
@@ -80,3 +82,54 @@ describe("applyPreviewAudioSettings", () => {
expect(graph.gain.gain.value).toBeCloseTo(0.5, 4);
});
});
+
+describe("resolveTimelineAudioPlayback", () => {
+ // A track placed 10s into the RAW timeline, source windowed to 2..8 (6s long).
+ const track: AxcutAudioTrack = {
+ id: "t1",
+ assetId: "a1",
+ timelineStartSec: 10,
+ durationSec: 20,
+ trimStartSec: 2,
+ trimEndSec: 8,
+ gainDb: 0,
+ mute: false,
+ label: "",
+ };
+
+ it("maps the playhead to a source position offset by the trim in-point", () => {
+ // 3s into the track's span → 2 (trimStart) + 3 = 5s of source.
+ expect(resolveTimelineAudioPlayback(13, track)).toEqual({ targetTimeSec: 5, shouldPlay: true });
+ });
+
+ it("does not play before the track starts, parked at the in-point", () => {
+ expect(resolveTimelineAudioPlayback(9, track)).toEqual({ targetTimeSec: 2, shouldPlay: false });
+ });
+
+ it("does not play past the window end, parked at the out-point", () => {
+ // Window is 6s (2..8), so timeline 10..16. At 16 it has just ended.
+ expect(resolveTimelineAudioPlayback(16, track)).toEqual({
+ targetTimeSec: 8,
+ shouldPlay: false,
+ });
+ });
+
+ it("never plays while muted, even inside its window", () => {
+ const muted = { ...track, mute: true };
+ expect(resolveTimelineAudioPlayback(13, muted)).toEqual({
+ targetTimeSec: 5,
+ shouldPlay: false,
+ });
+ });
+
+ it("uses the asset duration as the out-point when the tail isn't trimmed", () => {
+ const untrimmed = { ...track, trimStartSec: 0, trimEndSec: undefined, durationSec: 5 };
+ // Span is 10..15. At 14 → 4s of source, still playing.
+ expect(resolveTimelineAudioPlayback(14, untrimmed)).toEqual({
+ targetTimeSec: 4,
+ shouldPlay: true,
+ });
+ // At 15 the 5s file is over.
+ expect(resolveTimelineAudioPlayback(15, untrimmed).shouldPlay).toBe(false);
+ });
+});
diff --git a/src/components/ai-edition/VirtualPreview.playback.test.tsx b/src/components/ai-edition/VirtualPreview.playback.test.tsx
index f0389fe2a..d6b2d9f6c 100644
--- a/src/components/ai-edition/VirtualPreview.playback.test.tsx
+++ b/src/components/ai-edition/VirtualPreview.playback.test.tsx
@@ -207,3 +207,92 @@ describe("VirtualPreview playback across a clip boundary", () => {
expect(video.pauseCalls).toHaveLength(0);
});
});
+
+// Issue #350 — imported audio tracks follow the RAW virtual playhead. The
+// decision math is unit-tested in VirtualPreview.audio.test.ts; here we prove the
+// rAF loop applies it to the mounted <audio> element (seek + play/pause).
+function driveAudioEl(el: HTMLAudioElement) {
+ let currentTime = 0;
+ let paused = true;
+ Object.defineProperty(el, "currentTime", {
+ configurable: true,
+ get: () => currentTime,
+ set: (next: number) => {
+ currentTime = next;
+ },
+ });
+ Object.defineProperty(el, "paused", { configurable: true, get: () => paused });
+ Object.defineProperty(el, "duration", { configurable: true, get: () => 10 });
+ el.play = vi.fn(() => {
+ paused = false;
+ return Promise.resolve();
+ });
+ el.pause = vi.fn(() => {
+ paused = true;
+ });
+ return {
+ get currentTime() {
+ return currentTime;
+ },
+ };
+}
+
+describe("VirtualPreview imported audio tracks", () => {
+ // Windowed to source 1..3 (2s) and placed at timeline 2 → occupies 2..4.
+ const track = {
+ id: "trk",
+ assetId: "aud",
+ timelineStartSec: 2,
+ durationSec: 10,
+ trimStartSec: 1,
+ trimEndSec: 3,
+ gainDb: 0,
+ mute: false,
+ label: "",
+ };
+
+ function mountWithAudio() {
+ const sources: VideoSource[] = [{ id: "a1", src: "file:///tmp/a1.mp4", label: "a1" }];
+ const audioSources: VideoSource[] = [{ id: "aud", src: "file:///tmp/vo.mp3", label: "vo" }];
+ const { container } = render(
+ <VirtualPreview
+ videoSources={sources}
+ audioTracks={[track]}
+ audioSources={audioSources}
+ clips={[clip("c1", "a1", 0, 10, 0)]}
+ onTimeChange={vi.fn()}
+ />,
+ );
+ const videoEl = container.querySelector("video");
+ if (!videoEl) throw new Error("no <video>");
+ const video = driveVideo(videoEl as HTMLVideoElement);
+ act(() => fireEvent.loadedMetadata(videoEl));
+ const audioEl = container.querySelector<HTMLAudioElement>(
+ '[data-testid="preview-audio-track-trk"]',
+ );
+ if (!audioEl) throw new Error("no track <audio>");
+ return { video, audioEl, audio: driveAudioEl(audioEl) };
+ }
+
+ it("mounts one <audio> per track with the asset's URL", () => {
+ const { audioEl } = mountWithAudio();
+ expect(audioEl.getAttribute("src")).toBe("file:///tmp/vo.mp3");
+ });
+
+ it("plays inside the window at the trim-offset source time, pauses outside", () => {
+ const { video, audioEl, audio } = mountWithAudio();
+ video.play();
+ // virtualTime lands one tick after the video seek, and the audio loop reads
+ // last frame's virtualTime, so two ticks settle the decision.
+ video.seekTo(3); // virtual 3 → 1s into the 2..4 span
+ tick();
+ tick();
+ expect(audioEl.play).toHaveBeenCalled();
+ expect(audio.currentTime).toBeCloseTo(2, 1); // trimStart 1 + 1s in
+
+ video.seekTo(5); // virtual 5 → past the window end (4)
+ tick();
+ tick();
+ expect(audioEl.pause).toHaveBeenCalled();
+ });
+});
diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsx
index 804cfa5a5..b0d6d0685 100644
--- a/src/components/ai-edition/VirtualPreview.tsx
+++ b/src/components/ai-edition/VirtualPreview.tsx
@@ -5,7 +5,12 @@ import {
MAX_NATIVE_PLAYBACK_RATE,
} from "@/components/video-editor/types";
import { resolvePlaybackSegments } from "@/lib/ai-edition/document/timeline";
-import type { AxcutClip, AxcutTrimRange, AxcutZoomRegion } from "@/lib/ai-edition/schema";
+import type {
+ AxcutAudioTrack,
+ AxcutClip,
+ AxcutTrimRange,
+ AxcutZoomRegion,
+} from "@/lib/ai-edition/schema";
import { audioGainScalar } from "@/lib/ai-edition/store/editorSettings";
import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
import type { PlaybackClockRef } from "@/lib/ai-edition/timeline/playback-clock";
@@ -65,6 +70,32 @@ export function resolveAudioTrackPlayback(
};
}
+/**
+ * Where an imported audio track (issue #350) should sit against the RAW virtual
+ * timeline clock, and whether it should be playing there.
+ *
+ * A track occupies `[timelineStartSec, timelineStartSec + (trimEnd - trimStart)]`
+ * on the timeline; its source position is `trimStart` plus however far the
+ * playhead is into that span. Outside the span — or when muted — it parks at the
+ * nearer trim edge and stays paused, the same discipline `resolveAudioTrackPlayback`
+ * uses so the rAF never seeks an element into nothing.
+ *
+ * This is the RAW/document timeline the ruler, playhead and lane all use — NOT
+ * the trim-compressed output timeline — because that is where the track was
+ * placed (`useTimeline.addAudioTrack` seeds `timelineStartSec` from the playhead).
+ * The export mixes on the same RAW positions (see audio.rs), so the two agree.
+ */
+export function resolveTimelineAudioPlayback(virtualTimeSec: number, track: AxcutAudioTrack) {
+ const trimStart = Math.max(0, track.trimStartSec);
+ const trimEnd = track.trimEndSec ?? track.durationSec;
+ const windowLen = Math.max(0, trimEnd - trimStart);
+ const local = virtualTimeSec - track.timelineStartSec;
+ return {
+ targetTimeSec: Math.min(Math.max(trimStart, trimStart + local), trimEnd),
+ shouldPlay: !track.mute && local >= 0 && local < windowLen,
+ };
+}
+
export interface PreviewAudioGraph {
context: AudioContext;
gain: GainNode;
@@ -112,6 +143,11 @@ function findNextClipByTimelineOrder(
interface VirtualPreviewProps {
videoSources: VideoSource[];
+ /** Imported audio tracks to mix over the video (issue #350), and the file URLs
+ * their assets resolve to (keyed by assetId in `id`). Both default to empty, so
+ * a project with no imported audio behaves exactly as before. */
+ audioTracks?: AxcutAudioTrack[];
+ audioSources?: VideoSource[];
clips: AxcutClip[];
zoomRegions?: AxcutZoomRegion[];
speedRegions?: SpeedRegion[];
@@ -156,6 +192,8 @@ interface VirtualPreviewProps {
export function VirtualPreview({
videoSources,
+ audioTracks = [],
+ audioSources = [],
clips,
zoomRegions = [],
speedRegions = [],
@@ -426,6 +464,17 @@ export function VirtualPreview({
virtualDurationSecRef.current = virtualDurationSec;
const speedRegionsRef = useRef(speedRegions);
speedRegionsRef.current = speedRegions;
+ // Imported audio tracks (issue #350): the rAF reads these through refs, same as
+ // everything else it touches, so a track added/edited mid-playback is picked up
+ // without re-creating the loop. `audioTrackElsRef` maps a track id to its mounted
+ // <audio> element (registered by the ref callback on render).
+ const audioTracksRef = useRef(audioTracks);
+ audioTracksRef.current = audioTracks;
+ const audioTrackElsRef = useRef<Map<string, HTMLAudioElement>>(new Map());
+ const registerAudioTrackEl = useCallback((trackId: string, element: HTMLAudioElement | null) => {
+ if (element) audioTrackElsRef.current.set(trackId, element);
+ else audioTrackElsRef.current.delete(trackId);
+ }, []);
// Same reasoning as `clipsRef` above, for the one thing the rAF calls rather than reads:
// `seekToVirtualTime` is a `useCallback` whose deps include `clips`, so it takes a new
// identity on every clip mutation — a REORDER included. The rAF below is deliberately
@@ -471,6 +520,33 @@ export function VirtualPreview({
audio.pause();
}
}
+ // Imported audio tracks (issue #350): position each against the RAW
+ // virtual timeline it was placed on, play it only inside its window, and
+ // set its level from the track gain × the global output gain. Using
+ // `.volume` rather than a WebAudio node keeps the delicate
+ // primary/supplemental graph untouched; a boost past 0 dB clamps in the
+ // preview (volume maxes at 1) but is still written to the export.
+ const globalGain = audioGainScalar(audioGainDbRef.current);
+ for (const track of audioTracksRef.current) {
+ const el = audioTrackElsRef.current.get(track.id);
+ if (!el) continue;
+ const trackTarget = resolveTimelineAudioPlayback(virtualTimeSecRef.current, track);
+ if (el.playbackRate !== v.playbackRate) el.playbackRate = v.playbackRate;
+ el.volume = Math.min(1, audioGainScalar(track.gainDb) * globalGain);
+ if (Math.abs(el.currentTime - trackTarget.targetTimeSec) > 0.025) {
+ try {
+ el.currentTime = trackTarget.targetTimeSec;
+ } catch {
+ // media metadata not ready yet
+ }
+ }
+ if (!v.paused && trackTarget.shouldPlay && el.paused) {
+ const playback = el.play();
+ if (playback) void playback.catch(() => undefined);
+ } else if ((v.paused || !trackTarget.shouldPlay) && !el.paused) {
+ el.pause();
+ }
+ }
// Publish this frame's live position/rate for other media elements
// (webcam) to read directly — see playback-clock.ts for why this
// bypasses React state entirely.
@@ -1146,6 +1222,23 @@ export function VirtualPreview({
data-testid="preview-audio-supplemental"
/>
) : null}
+ {/* Imported audio tracks (issue #350). One element per track, kept in
+ sync by the rAF loop above via audioTrackElsRef. A track whose asset
+ URL isn't resolved yet is skipped rather than mounted src-less. */}
+ {audioTracks.map((track) => {
+ const src = audioSources.find((s) => s.id === track.assetId)?.src;
+ if (!src) return null;
+ return (
+ <audio
+ key={`audio-track:${track.id}`}
+ ref={(element) => registerAudioTrackEl(track.id, element)}
+ src={src}
+ preload="metadata"
+ aria-hidden="true"
+ data-testid={`preview-audio-track-${track.id}`}
+ />
+ );
+ })}
{/* Plus d'overlay ici du tout. « Loading preview… » reflétait l'état du
<video> CACHÉ (source horloge/audio), pas la preview RÉELLE — le canvas
natif, qui montre déjà une image valide pendant que le <video> re-seek.