Video Audio Overlay
Overlay audio onto a video using the useVideoAudioOverlay hook. Replace the video's original audio with a new track (e.g. AI-generated voiceover) or mix both together (e.g. background music under the original audio).
Important: Like all React hooks, useVideoAudioOverlay must only be called at the top level of React function components — not inside loops, conditions, or nested functions.
Import
import { useVideoAudioOverlay } from "@/hooks/use-video-audio-overlay";
When to Use
Use useVideoAudioOverlay for:
- Adding AI-generated voiceover (from
useAISpeech) onto a video - Adding background music from an uploaded audio file to a video
- Mixing background music with a video's original audio track
- Replacing the original audio of a video with a custom track
Supported Media Sources
The hook accepts these source types for both the video and audio inputs:
string— A URLBlob— Raw media dataFile— A local file{ url: string }— URL object shape for consistency with other platform APIs
All URL-based sources must be same-origin or CORS-enabled. Media stored on the platform (from useVideoJobStatus, useAISpeech, or useFileUpload) works automatically.
API Reference
Returns
overlay((params) => Promise<File | undefined>): Overlay audio onto a video and return the resultisProcessing(boolean):truewhile an overlay operation is runningprogress(number): Progress from 0 to 1 for the current operationerror(Error | null): Error state if the operation failscancel(() => void): Cancel a running overlay operationclearError(() => void): Clear any existing error
overlay Input
video(string | Blob | File | { url: string }, required): Video sourceaudio(string | Blob | File | { url: string }, required): Audio source to overlayaudioVolume(number, default:1): Overlay audio volume from 0 to 1videoVolume(number, default:0): Original video volume from 0 to 1; set above 0 to mix both tracksaudioOffset(number, default:0): Seconds to skip at the start of the audio trackwidth(number): Output width in pixels; defaults to the video's native widthheight(number): Output height in pixels; defaults to the video's native height
overlay Return Value
The returned File contains an MP4 video. Its name property already includes the .mp4 extension, so you can pass it directly to useDownload without specifying a filename. It also works with useFileUpload or any API that accepts File or Blob.
Audio Behavior
- Replace mode (default):
videoVolumedefaults to 0, so the video's original audio is muted and only the overlay audio plays - Mix mode: Set
videoVolume> 0 (e.g. 1) to hear both the original audio and the overlay audio together - If the audio is longer than the video, it is truncated when the video ends
- If the audio is shorter than the video, the remainder of the video plays without overlay audio
- Use
audioOffsetto skip into the audio track (e.g. skip a 2-second intro)
Example: Add AI Voiceover to a Video
import * as React from "react";
import { useAISpeech } from "@/hooks/use-ai";
import { useVideoAudioOverlay } from "@/hooks/use-video-audio-overlay";
import { useDownload } from "@/hooks/use-download";
export function VoiceoverDownload({ videoUrl }: { videoUrl: string }) {
const { generateSpeech } = useAISpeech();
const { overlay, isProcessing, progress } = useVideoAudioOverlay();
const { download } = useDownload();
const [status, setStatus] = React.useState("");
const handleCreate = async () => {
setStatus("Generating voiceover...");
const speech = await generateSpeech({
text: "Welcome to the heart of nature. Every morning, the forest awakens with a quiet symphony.",
});
if (!speech?.url) return;
setStatus("Adding voiceover to video...");
const result = await overlay({
video: videoUrl,
audio: speech.url,
});
if (result) {
setStatus("Done!");
download(result);
}
};
return (
<div>
<button onClick={handleCreate} disabled={isProcessing}>
Create narrated video
</button>
{isProcessing ? <progress value={progress * 100} /> : null}
{status ? <p>{status}</p> : null}
</div>
);
}
Example: Add Background Music While Keeping Original Audio
import type { ChangeEvent } from "react";
import { useVideoAudioOverlay } from "@/hooks/use-video-audio-overlay";
import { useFileUpload } from "@/hooks/use-file-upload";
import { useDownload } from "@/hooks/use-download";
export function BackgroundMusicOverlay({ videoUrl }: { videoUrl: string }) {
const { overlay, isProcessing, progress } = useVideoAudioOverlay();
const {
uploadFile,
file: uploadedFile,
isLoading: isUploading,
} = useFileUpload();
const { download } = useDownload();
const handleAudioUpload = async (event: ChangeEvent<HTMLInputElement>) => {
const audioFile = event.target.files?.[0];
if (audioFile) {
await uploadFile(audioFile);
}
};
const handleOverlay = async () => {
if (!uploadedFile) return;
const result = await overlay({
video: videoUrl,
audio: uploadedFile,
audioVolume: 0.3,
videoVolume: 1,
});
if (result) {
download(result);
}
};
return (
<div>
<input
type="file"
accept="audio/*"
onChange={handleAudioUpload}
disabled={isUploading}
/>
{uploadedFile ? <p>Music: {uploadedFile.name}</p> : null}
<button
onClick={handleOverlay}
disabled={isUploading || isProcessing || !uploadedFile}
>
{isProcessing
? `Processing... ${Math.round(progress * 100)}%`
: "Add music to video"}
</button>
{isProcessing ? <progress value={progress * 100} /> : null}
</div>
);
}
Key Behaviors
- Client-side processing — Processes media locally in the browser, so no server round-trip is required. The first operation may load browser-side processing assets
- Replace mode by default — The video's original audio is muted (
videoVolume: 0). SetvideoVolume> 0 to mix both tracks - Processing time varies — Processing depends on video length, resolution, whether the video needs resizing, audio settings, and device performance
- Reusable file output — The returned
Filecan be passed directly touseDownload(filename is optional; the file already has the correct name and extension),useFileUpload, or other platform APIs - Progress tracking — The
progressvalue (0 to 1) updates during processing - Cancellable — Call
cancel()to abort a running overlay operation - Automatic error handling — Errors always toast.
overlayresolves toundefinedinstead of rejecting. - Output format — Produces an MP4
File. The returnedFilealready includes the.mp4extension in its name, so pass it todownload(result)without hardcoding a file extension - Exclusive processing — Only one video stitch or audio overlay operation can run at a time
- Video quality — When the video must be re-encoded, the overlay uses the source video's bitrate when available, otherwise a fixed quality preset
Best Practices
- Generate or fetch both the video and audio before calling
overlayso the user sees generation progress separately from overlay progress - Use the
progressvalue to show a progress bar during processing - Use
useDownloadto let the user save the result - Use
useFileUploadif you want to persist the overlaid video to the platform - When mixing (keeping original audio), set
audioVolumelower (e.g. 0.3) to keep the overlay audio as background rather than competing with the original - Wait for the current video utility operation to finish before starting another stitch or audio overlay
Error Handling
const result = await overlay({
video: videoUrl,
audio: audioUrl,
});
if (!result) return;
Common errors:
"Audio volume must be a number between 0 and 1."—audioVolumemust be between 0 and 1"Video volume must be a number between 0 and 1."—videoVolumemust be between 0 and 1"Audio offset must be a non-negative number."—audioOffsetmust be 0 or greater"Another video operation is already running."— Wait for the current stitch or audio overlay operation to finish before starting another"Failed to fetch media source (...)."— A media URL could not be fetched (check CORS, URL validity, and network access)"Failed to load video."— The browser could not load video metadata for the source"Failed to overlay audio on video."— The video and audio could not be combined"Video operation was cancelled."or"Media load was cancelled."— The operation was cancelled viacancel()