> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pictory.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Background Music

> Add background music to videos with custom tracks or AI-selected music for enhanced engagement

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

<CardGroup cols={2}>
  <Card title="Custom Music" icon="music">
    Add your own music tracks from URLs
  </Card>

  <Card title="AI Music Selection" icon="wand-magic-sparkles">
    Let AI choose appropriate background music
  </Card>

  <Card title="Volume Control" icon="volume-high">
    Adjust music volume for perfect balance
  </Card>

  <Card title="Music Trimming" icon="scissors">
    Use specific portions of music tracks
  </Card>
</CardGroup>

## Before You Begin

Make sure you have:

* A [Pictory API key](https://app.pictory.ai/api-access)
* 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

<CodeGroup>
  ```bash npm theme={null}
  npm install axios
  ```

  ```bash pip theme={null}
  pip install requests
  ```
</CodeGroup>

## 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

<Note>
  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.
</Note>

## Complete Example

<CodeGroup>
  ```javascript Node.js theme={null}
  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();
  ```

  ```python Python theme={null}
  import requests
  import time
  import json

  API_BASE_URL = 'https://api.pictory.ai/pictoryapis'
  API_KEY = 'YOUR_API_KEY'

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

  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."
  )

  def create_video_with_background_music():
      try:
          print("Creating video with background music...")

          response = requests.post(
              f'{API_BASE_URL}/v2/video/storyboard/render',
              json={
                  '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
              }
          )
          response.raise_for_status()

          job_id = response.json()['data']['jobId']
          print("✓ Video creation started!")
          print(f"Job ID: {job_id}")

          # Monitor progress
          print("\nMonitoring video creation...")
          job_completed = False
          job_result = None

          while not job_completed:
              status_response = requests.get(
                  f'{API_BASE_URL}/v1/jobs/{job_id}',
                  headers={'Authorization': API_KEY}
              )
              status_response.raise_for_status()

              status = status_response.json()['data']['status']
              print(f"Status: {status}")

              if status == 'completed':
                  job_completed = True
                  job_result = status_response.json()
                  print("\n✓ Video with background music is ready!")
                  print(f"Video URL: {job_result['data']['videoURL']}")
              elif status == 'failed':
                  raise Exception(f"Video creation failed: {status_response.json()}")

              time.sleep(5)

          return job_result

      except requests.exceptions.RequestException as error:
          print(f"Error: {error}")
          if hasattr(error, 'response') and error.response is not None:
              print(f"Response: {error.response.text}")
          raise

  if __name__ == '__main__':
      create_video_with_background_music()
  ```
</CodeGroup>

## Background Music Configuration Parameters

### Music Settings

| Parameter                   | Type    | Required | Description                                                                                  |
| --------------------------- | ------- | -------- | -------------------------------------------------------------------------------------------- |
| `backgroundMusic.enabled`   | boolean | Yes      | Set to `true` to enable background music in the video                                        |
| `backgroundMusic.musicUrl`  | string  | No       | Public URL to your custom music file. Cannot be used with `autoMusic`.                       |
| `backgroundMusic.autoMusic` | boolean | No       | Set to `true` to let AI select appropriate background music. Cannot be used with `musicUrl`. |
| `backgroundMusic.volume`    | number  | No       | Music volume level from 0 (muted) to 1 (full volume). Default: 0.5                           |
| `backgroundMusic.clips`     | array   | No       | Array of music clip objects defining which portions of the music to use. Maximum 10 clips.   |

### Music Clips Configuration

| Parameter       | Type   | Required | Description                                                                  |
| --------------- | ------ | -------- | ---------------------------------------------------------------------------- |
| `clips[].start` | number | Yes      | Start time in seconds where the music clip begins                            |
| `clips[].end`   | number | Yes      | End time in seconds where the music clip ends. Must be greater than `start`. |

<Warning>
  **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
</Warning>

## Supported Audio Formats

| Format | Extension | Description                            | Best Used For                          |
| ------ | --------- | -------------------------------------- | -------------------------------------- |
| MP3    | `.mp3`    | Most common audio format (recommended) | General use, best compatibility        |
| WAV    | `.wav`    | Uncompressed audio, high quality       | High-quality music, professional audio |
| AAC    | `.aac`    | Advanced audio codec                   | Modern devices, streaming              |
| M4A    | `.m4a`    | Apple audio format                     | Music purchased from iTunes            |
| FLAC   | `.flac`   | Lossless compression                   | Audiophile quality, large files        |
| OGG    | `.ogg`    | Open-source format                     | Web streaming, game audio              |

<Tip>
  **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.
</Tip>

## Volume Level Reference

Choose the right volume based on your video's audio composition:

| Volume Value | Percentage | Effect           | Best Used For                                      |
| ------------ | ---------- | ---------------- | -------------------------------------------------- |
| 0            | 0%         | Muted            | No background music                                |
| 0.1-0.2      | 10-20%     | Very subtle      | Videos with heavy narration, podcasts              |
| 0.3-0.4      | 30-40%     | Soft background  | Videos with voice-over, professional presentations |
| 0.5          | 50%        | Balanced         | General use, balanced audio mix                    |
| 0.6-0.7      | 60-70%     | Noticeable music | Videos without voice-over, music videos            |
| 0.8-0.9      | 80-90%     | Prominent music  | Emphasis on music, minimal narration               |
| 1.0          | 100%       | Full volume      | Pure background music, no other audio              |

<Note>
  **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
</Note>

## Using AI-Selected Music

Let the AI automatically choose appropriate background music for your video:

<CodeGroup>
  ```javascript Node.js theme={null}
  {
    backgroundMusic: {
      enabled: true,
      autoMusic: true,          // AI selects appropriate music
      volume: 0.4               // Adjust volume as needed
    }
  }
  ```

  ```python Python theme={null}
  {
      'backgroundMusic': {
          'enabled': True,
          'autoMusic': True,    # AI selects appropriate music
          'volume': 0.4         # Adjust volume as needed
      }
  }
  ```
</CodeGroup>

**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

```javascript theme={null}
{
  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

```javascript theme={null}
{
  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)

```javascript theme={null}
{
  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.

<Tip>
  **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.
</Tip>

## Common Use Cases

### Educational Videos with Narration

```javascript theme={null}
{
  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

```javascript theme={null}
{
  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)

```javascript theme={null}
{
  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

```javascript theme={null}
{
  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

<AccordionGroup>
  <Accordion title="Balance Music with Voice-Over">
    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
  </Accordion>

  <Accordion title="Choose Appropriate Music for Content">
    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
  </Accordion>

  <Accordion title="Use Royalty-Free Music">
    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 is copyright-safe
    * **Attribution**: Follow license requirements for attribution when needed
  </Accordion>

  <Accordion title="Optimize Music File Accessibility">
    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 will not 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
  </Accordion>

  <Accordion title="Strategic Clip Usage">
    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)
  </Accordion>
</AccordionGroup>

## Troubleshooting

<AccordionGroup>
  <Accordion title="Error: Cannot access music file">
    **Problem:** The API cannot download or process your music file.

    **Solution:**

    * Verify the URL is publicly accessible (test in incognito browser)
    * Ensure it is 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)
  </Accordion>

  <Accordion title="Music is too loud or too quiet">
    **Problem:** Background music volume does not 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
  </Accordion>

  <Accordion title="Error: Cannot use musicUrl and autoMusic together">
    **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 }`
  </Accordion>

  <Accordion title="Music Does Not Loop Properly">
    **Problem:** Music ends abruptly or does not 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
  </Accordion>

  <Accordion title="Clip Times Do Not Work as Expected">
    **Problem:** Music clips do not 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 do not exceed the music file duration
    * Test clip times using an audio player first
    * Maximum 10 clips per video
    * Clips play in the order they are defined in the array
  </Accordion>

  <Accordion title="No music in final video">
    **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
  </Accordion>
</AccordionGroup>

## 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

```javascript theme={null}
{
  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:

<CardGroup cols={2}>
  <Card title="AI Voice-Over" icon="microphone" href="/guides/text-to-video/ai-voiceover">
    Add narration to videos with background music
  </Card>

  <Card title="Brand Settings" icon="palette" href="/guides/branding-customization/brand-settings">
    Apply consistent branding with background music
  </Card>

  <Card title="Intro/Outro Videos" icon="clapperboard" href="/guides/advanced-features/intro-outro">
    Add intro and outro sequences with music
  </Card>

  <Card title="Custom Subtitle Styling" icon="closed-captioning" href="/guides/branding-customization/custom-subtitle-style">
    Style subtitles to complement your music videos
  </Card>
</CardGroup>

## API Reference

For complete technical details, see:

* [Render Storyboard Video](/api-reference/videos/render-storyboard-video) - Full API specification including backgroundMusic
* [Get Job Status](/api-reference/jobs/get-video-render-job-by-id) - Monitor job status and get video URLs
