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 URL
  • Blob — Raw media data
  • File — 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 result
  • isProcessing (boolean): true while an overlay operation is running
  • progress (number): Progress from 0 to 1 for the current operation
  • error (Error | null): Error state if the operation fails
  • cancel (() => void): Cancel a running overlay operation
  • clearError (() => void): Clear any existing error

overlay Input

  • video (string | Blob | File | { url: string }, required): Video source
  • audio (string | Blob | File | { url: string }, required): Audio source to overlay
  • audioVolume (number, default: 1): Overlay audio volume from 0 to 1
  • videoVolume (number, default: 0): Original video volume from 0 to 1; set above 0 to mix both tracks
  • audioOffset (number, default: 0): Seconds to skip at the start of the audio track
  • width (number): Output width in pixels; defaults to the video's native width
  • height (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): videoVolume defaults 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 audioOffset to 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

  1. 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
  2. Replace mode by default — The video's original audio is muted (videoVolume: 0). Set videoVolume > 0 to mix both tracks
  3. Processing time varies — Processing depends on video length, resolution, whether the video needs resizing, audio settings, and device performance
  4. Reusable file output — The returned File can be passed directly to useDownload (filename is optional; the file already has the correct name and extension), useFileUpload, or other platform APIs
  5. Progress tracking — The progress value (0 to 1) updates during processing
  6. Cancellable — Call cancel() to abort a running overlay operation
  7. Automatic error handling — Errors always toast. overlay resolves to undefined instead of rejecting.
  8. Output format — Produces an MP4 File. The returned File already includes the .mp4 extension in its name, so pass it to download(result) without hardcoding a file extension
  9. Exclusive processing — Only one video stitch or audio overlay operation can run at a time
  10. 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

  1. Generate or fetch both the video and audio before calling overlay so the user sees generation progress separately from overlay progress
  2. Use the progress value to show a progress bar during processing
  3. Use useDownload to let the user save the result
  4. Use useFileUpload if you want to persist the overlaid video to the platform
  5. When mixing (keeping original audio), set audioVolume lower (e.g. 0.3) to keep the overlay audio as background rather than competing with the original
  6. 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." — audioVolume must be between 0 and 1
  • "Video volume must be a number between 0 and 1." — videoVolume must be between 0 and 1
  • "Audio offset must be a non-negative number." — audioOffset must 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 via cancel()