Skip to main content
This guide shows you how to add background music to your videos. Choose between providing your own custom music files or letting AI select appropriate tracks automatically. Perfect for creating engaging videos with professional audio layers.

What You’ll Learn

Custom Music

Add your own music tracks from URLs

AI Music Selection

Let AI choose appropriate background music

Volume Control

Adjust music volume for perfect balance

Music Trimming

Use specific portions of music tracks

Before You Begin

Make sure you have:
  • A Pictory API key (get one here)
  • Node.js or Python installed on your machine
  • Music file accessible via public URL (for custom music)
  • Basic understanding of video creation with Pictory API
npm install axios

How Background Music Works

When you add background music to a video:
  1. Music Selection - You provide a custom music URL or enable AI auto-selection
  2. Audio Processing - The music file is accessed and processed
  3. Volume Adjustment - Music volume is set according to your specifications
  4. Clip Extraction - Specific portions of the music are extracted (if clips defined)
  5. Audio Mixing - Music is mixed with voice-over and video audio
  6. Duration Matching - Music loops or fades to match video length
  7. Video Rendering - Final video is rendered with all audio layers combined
Background music automatically loops if the music track is shorter than your video duration. The music fades out gracefully at the end of the video for a professional finish.

Complete Example

import axios from "axios";

const API_BASE_URL = "https://api.pictory.ai/pictoryapis";
const API_KEY = "YOUR_API_KEY";

// Your custom music file URL (must be publicly accessible)
const MUSIC_URL = "https://example.com/your-music-file.mp3";

const STORY_TEXT =
  "AI is poised to significantly impact educators and course creators on social media. " +
  "By automating tasks like content generation, visual design, and video editing, " +
  "AI will save time and enhance consistency.";

async function createVideoWithBackgroundMusic() {
  try {
    console.log("Creating video with background music...");

    const response = await axios.post(
      `${API_BASE_URL}/v2/video/storyboard/render`,
      {
        videoName: "video_with_background_music",

        // Background music configuration
        backgroundMusic: {
          enabled: true,                         // Enable background music
          musicUrl: MUSIC_URL,                   // Your custom music file URL
          volume: 0.3,                           // 30% volume (0-1)

          // Optional: Use specific portions of the music
          clips: [
            {
              start: 10,                         // Start at 10 seconds
              end: 70,                           // End at 70 seconds (60s clip)
            },
          ],
        },

        // Scene configuration
        scenes: [
          {
            story: STORY_TEXT,
            createSceneOnNewLine: true,
            createSceneOnEndOfSentence: true,
          },
        ],
      },
      {
        headers: {
          "Content-Type": "application/json",
          Authorization: API_KEY,
        },
      }
    );

    const jobId = response.data.data.jobId;
    console.log("✓ Video creation started!");
    console.log("Job ID:", jobId);

    // Monitor progress
    console.log("\nMonitoring video creation...");
    let jobCompleted = false;
    let jobResult = null;

    while (!jobCompleted) {
      const statusResponse = await axios.get(
        `${API_BASE_URL}/v1/jobs/${jobId}`,
        {
          headers: { Authorization: API_KEY },
        }
      );

      const status = statusResponse.data.data.status;
      console.log("Status:", status);

      if (status === "completed") {
        jobCompleted = true;
        jobResult = statusResponse.data;
        console.log("\n✓ Video with background music is ready!");
        console.log("Video URL:", jobResult.data.videoURL);
      } else if (status === "failed") {
        throw new Error("Video creation failed: " + JSON.stringify(statusResponse.data));
      }

      await new Promise(resolve => setTimeout(resolve, 5000));
    }

    return jobResult;
  } catch (error) {
    console.error("Error:", error.response?.data || error.message);
    throw error;
  }
}

createVideoWithBackgroundMusic();

Background Music Configuration Parameters

Music Settings

ParameterTypeRequiredDescription
backgroundMusic.enabledbooleanYesSet to true to enable background music in the video
backgroundMusic.musicUrlstringNoPublic URL to your custom music file. Cannot be used with autoMusic.
backgroundMusic.autoMusicbooleanNoSet to true to let AI select appropriate background music. Cannot be used with musicUrl.
backgroundMusic.volumenumberNoMusic volume level from 0 (muted) to 1 (full volume). Default: 0.5
backgroundMusic.clipsarrayNoArray of music clip objects defining which portions of the music to use. Maximum 10 clips.

Music Clips Configuration

ParameterTypeRequiredDescription
clips[].startnumberYesStart time in seconds where the music clip begins
clips[].endnumberYesEnd time in seconds where the music clip ends. Must be greater than start.
Mutual Exclusivity: You cannot use both musicUrl and autoMusic in the same request. Choose one:
  • Use musicUrl for custom music tracks
  • Use autoMusic: true for AI-selected music

Supported Audio Formats

FormatExtensionDescriptionBest Used For
MP3.mp3Most common audio format (recommended)General use, best compatibility
WAV.wavUncompressed audio, high qualityHigh-quality music, professional audio
AAC.aacAdvanced audio codecModern devices, streaming
M4A.m4aApple audio formatMusic purchased from iTunes
FLAC.flacLossless compressionAudiophile quality, large files
OGG.oggOpen-source formatWeb streaming, game audio
Best Format: Use MP3 with 128-320 kbps bitrate for the best balance of quality and processing speed. Ensure music files are accessible via public, direct download URLs.

Volume Level Reference

Choose the right volume based on your video’s audio composition:
Volume ValuePercentageEffectBest Used For
00%MutedNo background music
0.1-0.210-20%Very subtleVideos with heavy narration, podcasts
0.3-0.430-40%Soft backgroundVideos with voice-over, professional presentations
0.550%BalancedGeneral use, balanced audio mix
0.6-0.760-70%Noticeable musicVideos without voice-over, music videos
0.8-0.980-90%Prominent musicEmphasis on music, minimal narration
1.0100%Full volumePure background music, no other audio
Voice-Over Recommendations:
  • With AI voice-over: Use 0.2-0.4 to ensure narration is clearly heard
  • Without voice-over: Use 0.5-0.8 for more prominent background music
  • With original video audio: Use 0.2-0.3 to avoid overwhelming existing audio

Using AI-Selected Music

Let the AI automatically choose appropriate background music for your video:
{
  backgroundMusic: {
    enabled: true,
    autoMusic: true,          // AI selects appropriate music
    volume: 0.4               // Adjust volume as needed
  }
}
How AI Selection Works:
  • AI analyzes your video content and theme
  • Selects music that matches the video’s mood and pacing
  • Chooses from a library of royalty-free music tracks
  • No need to provide your own music URL

Using Music Clips

Extract and use specific portions of a music track:

Single Clip Example

{
  backgroundMusic: {
    enabled: true,
    musicUrl: "https://example.com/music.mp3",
    volume: 0.5,
    clips: [
      { start: 30, end: 90 }      // Use seconds 30-90 (1 minute clip)
    ]
  }
}
Result: Uses only seconds 30-90 from the music file, looping if needed.

Multiple Clips Example

{
  backgroundMusic: {
    enabled: true,
    musicUrl: "https://example.com/music.mp3",
    volume: 0.4,
    clips: [
      { start: 0, end: 30 },      // Intro section (30 seconds)
      { start: 90, end: 120 },    // Chorus section (30 seconds)
      { start: 180, end: 210 }    // Outro section (30 seconds)
    ]
  }
}
Result: Uses three different portions of the music, played sequentially.

Full Track (No Clips)

{
  backgroundMusic: {
    enabled: true,
    musicUrl: "https://example.com/music.mp3",
    volume: 0.5
    // No clips specified - uses entire track
  }
}
Result: Uses the entire music track from start to finish.
Clip Strategy: Use clips to extract the best portions of a song (e.g., just the upbeat chorus, skip long intros). Maximum 10 clips per video.

Common Use Cases

Educational Videos with Narration

{
  backgroundMusic: {
    enabled: true,
    autoMusic: true,                // AI-selected background music
    volume: 0.25                    // Quiet to not overpower voice-over
  },
  voiceOver: {
    enabled: true,
    aiVoices: [{ speaker: "Emma", speed: 100 }]
  }
}
Result: Subtle background music that enhances the video without interfering with educational narration.

Marketing Videos with Energetic Music

{
  backgroundMusic: {
    enabled: true,
    musicUrl: "https://storage.example.com/upbeat-corporate.mp3",
    volume: 0.6,                    // Prominent but not overwhelming
    clips: [
      { start: 15, end: 75 }        // Use the energetic chorus section
    ]
  }
}
Result: Engaging, energetic music that drives the marketing message forward.

Social Media Content (No Voice-Over)

{
  backgroundMusic: {
    enabled: true,
    musicUrl: "https://storage.example.com/trending-track.mp3",
    volume: 0.75                    // Higher volume, no voice-over to compete with
  }
}
Result: Music-driven social media video with subtitles for context.

Professional Presentations

{
  backgroundMusic: {
    enabled: true,
    musicUrl: "https://storage.example.com/corporate-ambient.mp3",
    volume: 0.3,                    // Professional, subtle background
    clips: [
      { start: 0, end: 120 }        // Use calm intro section
    ]
  },
  voiceOver: {
    enabled: true,
    aiVoices: [{ speaker: "Matthew", speed: 95 }]
  }
}
Result: Professional presentation with subtle, non-distracting background music and clear narration.

Best Practices

Ensure music complements rather than competes with narration:
  • With Voice-Over: Use volume 0.2-0.4 for background music
  • Clear Narration: Keep music soft enough that every word is heard
  • Voice Emphasis: Music should enhance, not distract from the message
  • Test Levels: Preview videos to ensure proper audio balance
  • Consistent Volume: Maintain consistent music volume throughout
Match music style to your video’s purpose and audience:
  • Educational Content: Use calm, neutral background music
  • Marketing Videos: Choose upbeat, energetic tracks
  • Professional Presentations: Use subtle, corporate-style music
  • Social Media: Opt for trending or popular music styles
  • Emotional Content: Match music mood to video emotion (inspiring, somber, etc.)
  • Brand Alignment: Ensure music fits your brand identity
Avoid copyright issues by using properly licensed music:
  • Royalty-Free Libraries: Use sites like AudioJungle, Epidemic Sound, Artlist
  • Creative Commons: Verify licenses allow commercial use
  • Stock Music: Invest in quality stock music libraries
  • Original Music: Commission custom tracks for unique branding
  • AI Music: Use AI-generated music that’s copyright-safe
  • Attribution: Follow license requirements for attribution when needed
Ensure your music files can be accessed by the API:
  • Public URLs: Upload to cloud storage (AWS S3, Google Drive, Dropbox)
  • Direct Links: Use direct download links, not streaming or preview URLs
  • Stable URLs: Ensure links won’t expire during processing
  • Test Access: Verify URLs work in incognito browser
  • File Size: Keep files under 50MB for faster processing
  • Format: Use MP3 format for best compatibility
Use music clips to enhance your video effectively:
  • Skip Intros: Start clips after long musical intros
  • Use Choruses: Extract upbeat, engaging portions of songs
  • Avoid Vocals: Consider instrumental tracks or sections for clarity
  • Loop Planning: Choose clips that loop naturally if needed
  • Length Matching: Use clips that align with your video duration
  • Multiple Clips: Vary music across different video sections (max 10)

Troubleshooting

Problem: The API cannot download or process your music file.Solution:
  • Verify the URL is publicly accessible (test in incognito browser)
  • Ensure it’s a direct download link, not a streaming or preview link
  • For Google Drive: Right-click → Share → “Anyone with the link” → Copy link
  • For Dropbox: Share → Create link → change “dl=0” to “dl=1” at end of URL
  • Check file hasn’t been deleted or moved
  • Verify file format is supported (MP3, WAV, AAC, M4A)
  • Ensure file size is reasonable (under 50MB recommended)
Problem: Background music volume doesn’t balance well with other audio.Solution:
  • Adjust the volume parameter (range: 0-1)
  • With voice-over: Try 0.2-0.4 for subtle background
  • Without voice-over: Try 0.5-0.8 for more prominent music
  • Test different values to find the right balance
  • Consider the original music file’s volume level
  • Use audio editing software to normalize music before uploading
Problem: Request fails because both musicUrl and autoMusic are specified.Solution:
  • Choose one method: custom music OR AI-selected music
  • Remove musicUrl if using autoMusic: true
  • Remove autoMusic if using musicUrl
  • Example with AI music: { enabled: true, autoMusic: true, volume: 0.4 }
  • Example with custom music: { enabled: true, musicUrl: "...", volume: 0.4 }
Problem: Music ends abruptly or doesn’t loop smoothly.Solution:
  • The API automatically loops music shorter than the video
  • Choose music that loops naturally (same start and end)
  • Use music editing software to create seamless loops
  • Consider using full-length tracks that match video duration
  • Use multiple clips to control exactly which portions play
  • Music automatically fades out at video end for smooth finish
Problem: Music clips don’t extract the expected portions of the track.Solution:
  • Verify start time is less than end time
  • Check that times are in seconds, not minutes
  • Ensure clip times don’t exceed the music file duration
  • Test clip times using an audio player first
  • Maximum 10 clips per video
  • Clips play in the order they’re defined in the array
Problem: Created video but background music is missing.Solution:
  • Verify enabled: true in backgroundMusic configuration
  • Check volume is not set to 0 (muted)
  • Ensure either musicUrl or autoMusic: true is specified
  • Verify job completed successfully without errors
  • Check API response for any warnings about music processing
  • Test with AI music first to isolate custom URL issues
  • Verify music file URL is accessible and in supported format

Music Looping and Fading

Automatic Looping

When your music track is shorter than the video:
  • Music automatically loops from the beginning
  • Seamless looping for music designed to loop
  • Use loop-friendly tracks for best results

Automatic Fade-Out

At the end of the video:
  • Music fades out gracefully over the last 2-3 seconds
  • Prevents abrupt audio cutoff
  • Creates professional-sounding finish

Using Clips to Control Looping

{
  clips: [
    { start: 30, end: 90 }    // Loop only the 30-90 second portion
  ]
}
Only the specified clip portion loops, not the entire track.

Next Steps

Enhance your videos with these complementary features:

API Reference

For complete technical details, see: