How to Build an AI Background Music (BGM) & Video Soundtrack Sync Pipeline via API and MCP (2026 Guide)
Learn how to generate instrumental AI background music from 5 to 300 seconds via REST API and MCP, choose between MP3 and lossless WAV masters, and automatically mix, fade, and sync tracks onto video without running local FFmpeg workers.
Adding custom soundtracks to generated or edited video usually forces engineering teams into a fragmented stack. Most AI music APIs lock you into monthly seat subscriptions or rigid 30-second credit packs, while still leaving you to download audio files, compute clip durations, configure ducking curves, and maintain a fleet of FFmpeg workers just to mux audio onto an MP4.
This guide shows how to build an end-to-end AI background music (BGM) generation and video soundtrack sync pipeline using a single pay-as-you-go API key. You will compose instrumental tracks from 5 to 300 seconds via Lumoz BGM (lumoz-bgm), merge and duck audio onto video through the serverless video-audio-merger microservice, and run the entire workflow inside Claude or Cursor via Lumoz MCP.
Why Existing AI Music APIs Stall in Production Video Pipelines
Developers building automated video editors, marketing reel generators, e-learning tools, or game asset pipelines run into four recurring bottlenecks when integrating standalone audio APIs:
- Monthly subscription waste: Many commercial music APIs start at $19/month to $199/month regardless of whether your app renders 40 videos one week and 4,000 the next. Unused credits expire every billing cycle.
- Accidental vocals on background beds: Text-to-music models tuned for full songs frequently inject synthetic singing or vocal chops when prompts are underspecified, clashing directly with product narration or dialogue.
- Short, inflexible clip lengths: Fixed 30-second outputs force awkward crossfade stitching on 60-second explainers or 3-minute ambient loops, while short 10-second social reels overpay for full-track generations.
- DIY FFmpeg infrastructure: Generating the MP3 is only half the pipeline. Your backend still has to probe video length, loop or trim the soundtrack, apply fade-in/fade-out envelopes, duck music volume under speech, and remux streams cleanly.
On LumozAI, audio generation and video muxing share one unified billing ledger with per-second music pricing and zero monthly commitments.
AI Background Music APIs Compared (2026)
Before wiring an audio endpoint into production, compare how major developer music APIs handle pricing, duration flexibility, instrumental locking, and post-production muxing:
| Platform / API | Pricing Structure | Duration Range | Instrumental Lock | Built-in Video Muxing | Best Fit |
|---|---|---|---|---|---|
LumozAI (lumoz-bgm) |
Pay-as-you-go: $0.02/sec ($0.30 per 15s) | 5s to 300s (5 min) | Native (force_instrumental: true) |
Yes (video-audio-merger at $0.005/run) |
Automated video, SaaS, and MCP agent pipelines |
| Stable Audio API | Credit packs (~$0.20 / generation) | Fixed-tier audio windows | Prompt-guided | No (external FFmpeg required) | Standalone ambient beds and SFX |
| MusicAPI | Monthly subscriptions (~$19–$833+/mo) | Song-length tiers | Optional instrumental flag | No (external FFmpeg required) | Full-song generation and stem splitting |
| Mubert API | Business plans (~$199/mo+) | Continuous streams / tracks | Instrumental-focused | No | Ambient focus, fitness, and live streaming apps |
| Loudly AI Music API | Custom enterprise quotes | Custom track lengths | Yes (stem-aware) | No | Enterprise platforms requiring custom contracts |
Step 1: Generate Custom BGM via the Unified REST API
Lumoz BGM is exposed through the unified v4 inference endpoint at POST https://lumozai.com/api/v4/run. Because audio rendering scales with track length, short 5–15 second stingers complete quickly, while 60–300 second compositions should use asynchronous execution with either status polling or a webhook callback.
Core Request Parameters for lumoz-bgm
model: Set to"lumoz-bgm".prompt: Text description covering genre, mood, instruments, tempo, and arrangement.duration: Target duration in seconds from5to300(default15). Alternatively, passmusic_length_msfrom5000to300000for millisecond precision.force_instrumental: Boolean (defaulttrue). Strips vocal elements so the track functions cleanly as background music.output_format: Choosemp3_high_quality(192kbps, default),mp3_standard(128kbps),wav_cd_quality(44.1kHz lossless),wav_24khz, orwav_16khz.async&webhook: Optional boolean and HTTPS callback URL for non-blocking jobs.
cURL Quickstart (Synchronous 15-Second BGM)
curl -X POST "https://lumozai.com/api/v4/run" \
-H "Authorization: Bearer YOUR_LUMOZ_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "lumoz-bgm",
"prompt": "Warm minimalist tech product launch soundtrack, muted Rhodes chords, crisp sub-bass pulse, 108 BPM, spacious mix for voiceover",
"duration": 15,
"force_instrumental": true,
"output_format": "mp3_high_quality"
}'
Python Async Polling Pattern (30–300 Second Soundtracks)
For longer compositions, pass "async": true to receive a request_id immediately and poll GET https://lumozai.com/api/v4/status/{request_id} until status transitions to "success":
import os
import time
import requests
API_KEY = os.environ["LUMOZ_API_KEY"]
HEADERS = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
}
def generate_bgm(prompt: str, duration: int = 45, output_format: str = "mp3_high_quality") -> str:
payload = {
"model": "lumoz-bgm",
"prompt": prompt,
"duration": duration,
"force_instrumental": True,
"output_format": output_format,
"async": True,
}
resp = requests.post("https://lumozai.com/api/v4/run", json=payload, headers=HEADERS, timeout=30)
resp.raise_for_status()
job = resp.json()
if job.get("status") == "success" and job.get("output"):
return job["output"]
request_id = job["request_id"]
status_url = f"https://lumozai.com/api/v4/status/{request_id}"
for _ in range(90):
poll = requests.get(status_url, headers=HEADERS, timeout=15).json()
if poll.get("status") == "success":
return poll["output"]
if poll.get("status") in ("failed", "error"):
raise RuntimeError(f"BGM generation failed: {poll}")
time.sleep(2)
raise TimeoutError(f"Timed out waiting for BGM job {request_id}")
bgm_url = generate_bgm(
prompt="Atmospheric lo-fi beats with vinyl crackle, soft upright piano, gentle brushed snare, 82 BPM",
duration=45,
)
print("Generated BGM URL:", bgm_url)
Step 2: Prompt Engineering and Audio Format Selection
Writing BGM Prompts That Sit Cleanly Behind Voiceovers
Music generated as a standalone song often competes with human speech in the 1 kHz to 4 kHz frequency band. When generating soundtracks meant to accompany narration or UI demos, structure prompts around four elements:
- Core genre and instrumentation: Specify concrete instruments (for example, muted electric piano, warm analog pad, plucked acoustic guitar, soft percussive shaker) rather than vague adjectives like "inspiring."
- Tempo and rhythmic density: Include BPM and groove hints (such as 96 BPM steady pulse or half-time ambient groove) so pacing matches your video cuts.
- Mix headroom cue: Phrases like spacious midrange, gentle low-pass warmth, minimal busy lead melodies keep the track unobtrusive beneath narration.
- Strict instrumental lock: Keep
force_instrumentalset totruefor BGM so no phantom vocalizations interrupt dialogue.
Choosing the Right Output Format
mp3_high_quality(192kbps): Best default for social videos, web players, and SaaS exports—compact file sizes with clean high-frequency transients.mp3_standard(128kbps): Ideal for lightweight mobile previews or high-volume draft workflows.wav_cd_quality(44.1kHz lossless): Use when handing audio to downstream DAWs, NLE timelines (Premiere, DaVinci Resolve), or multi-pass mastering pipelines.wav_24khz/wav_16khz: Tailored for voice-band broadcast containers or embedded telephony/kiosk playback.
Step 3: Sync, Duck, and Merge BGM onto Video Without Local FFmpeg
Once your soundtrack URL is ready, you do not need to download the MP3 or spawn local FFmpeg processes. Suppose you created a product clip with Photo to Video Animator and upscaled it via AI Video Upscaler. You can attach, loop, fade, and volume-balance your generated BGM in one API call to POST https://lumozai.com/api/v1/services/video-audio-merger/run at a flat $0.005 per run.
Key video-audio-merger Parameters
video&audio: HTTPS URLs (or base64 data URIs) for the source MP4/WEBM/MOV video and MP3/WAV audio.mode: Use"replace"for silent AI-generated video clips, or"mix"to blend BGM underneath existing dialogue or sound effects.audio_volume(0.0–3.0) &video_volume(0.0–2.0): Setaudio_volume: 0.22andvideo_volume: 1.0in"mix"mode to duck background music cleanly under speech.loop&trim_to_video: Setloop: trueif the BGM is shorter than the clip, andtrim_to_video: trueso the soundtrack cuts cleanly at the final video frame.fade_in&fade_out: Smooth transition durations in seconds (for example,0.5second fade-in and2.0second fade-out).audio_delay_ms: Optional millisecond offset if the soundtrack should enter after an intro title card.
End-to-End TypeScript Pipeline: Generate BGM + Mix with Video
const LUMOZ_API_KEY = process.env.LUMOZ_API_KEY!;
async function scoreAndMergeVideo(videoUrl: string, musicPrompt: string, durationSec: number) {
// 1. Compose instrumental BGM track ($0.02/sec)
const bgmRes = await fetch("https://lumozai.com/api/v4/run", {
method: "POST",
headers: {
Authorization: `Bearer ${LUMOZ_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "lumoz-bgm",
prompt: musicPrompt,
duration: durationSec,
force_instrumental: true,
output_format: "mp3_high_quality",
}),
});
const bgmData = await bgmRes.json();
if (bgmData.status !== "success" || !bgmData.output) {
throw new Error(`BGM failed: ${JSON.stringify(bgmData)}`);
}
// 2. Mix BGM underneath original video audio with fade-out ($0.005/run)
const mergeRes = await fetch("https://lumozai.com/api/v1/services/video-audio-merger/run", {
method: "POST",
headers: {
Authorization: `Bearer ${LUMOZ_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
video: videoUrl,
audio: bgmData.output,
mode: "mix",
audio_volume: 0.25,
video_volume: 1.0,
loop: true,
trim_to_video: true,
fade_in: 0.5,
fade_out: 2.0,
}),
});
const mergeData = await mergeRes.json();
if (mergeData.status !== "success") {
throw new Error(`Video merge failed: ${JSON.stringify(mergeData)}`);
}
return {
bgmUrl: bgmData.output,
finalVideoUrl: mergeData.output,
mergeCost: mergeData.cost,
};
}
Step 4: Automate Soundtracks in Claude and Cursor with Lumoz MCP
If you build creative workflows inside an AI IDE or desktop assistant, Lumoz MCP exposes both lumoz_generate_bgm and lumoz_run_microservice (for video-audio-merger) directly as native agent tools over Server-Sent Events at https://lumozai.com/api/mcp.
Add the Lumoz MCP endpoint to your Claude Desktop or Cursor mcp.json configuration:
{
"mcpServers": {
"lumozai": {
"url": "https://lumozai.com/api/mcp",
"headers": {
"Authorization": "Bearer YOUR_LUMOZ_API_KEY"
}
}
}
}
Once connected, you can prompt your agent in plain English—for example: "Use lumoz_generate_bgm to create a 20-second upbeat synthwave instrumental at high quality MP3, then run video-audio-merger via lumoz_run_microservice in mix mode at 0.25 audio_volume with a 1.5s fade_out onto https://cdn.example.com/demo.mp4." Pairing this with cover art from Social Thumbnail Maker lets one agent produce a publish-ready video asset end to end.
Cost Breakdown & Production Checklist
Because LumozAI charges strictly per generated second for music and per execution for microservices, unit economics stay predictable across short clips and long-form videos. Check the LumozAI pricing page for full wallet and model rates.
- 15-second BGM + Video Sync: $0.30 (
lumoz-bgmat $0.02/sec) + $0.005 (video-audio-merger) = $0.305 total. - 30-second BGM + Video Sync: $0.60 + $0.005 = $0.605 total.
- 60-second BGM + Video Sync: $1.20 + $0.005 = $1.205 total.
- 300-second (5-minute) ambient soundtrack: $6.00 with zero monthly seat fees.
Before deploying to production, verify these four safeguards in your job handler:
- Enable
async: truewith webhooks or status polling wheneverdurationexceeds 20 seconds to prevent HTTP client timeouts. - Keep
force_instrumental: truefor any track intended to sit behind TTS or human narration. - Always pass
trim_to_video: truealongside a1.5–2.5secondfade_outinvideo-audio-mergerso soundtracks never clip abruptly at the end of a video. - Persist the returned CDN URLs immediately to your own object storage or database record after job completion.
Recommended from LumozAI
How to Build a Multilingual AI Voice Cloning & TTS Pipeline via OpenAI-Compatible API and MCP (2026 Guide)
Learn how to clone custom voices from 10-120s samples, synthesize speech across 90+ auto-detected languages via an OpenAI-compatible API and REST v4, pair custom BGM with video muxing, and automate voiceovers in Claude or Cursor with MCP.
How to Build a 4K AI Video Upscaling Pipeline via REST API and MCP (2026 Guide)
Learn how to upscale 480p, 720p, and 1080p clips to crisp 4K via a pay-as-you-go REST API, async webhooks, and MCP—plus how to pair video super-resolution with audio muxing and keyframe upscaling.
How to Build a Transparent PNG Generation Pipeline Using an AI Background Removal API (2026 Guide)
Learn how to generate lossless 32-bit transparent PNGs programmatically using RMBG-2.0 and BiRefNet via REST API and MCP, with Python, Node.js, and cURL examples at $0.005 per image.