> This is a page from the ElevenLabs documentation. For a complete page index, fetch https://elevenlabs.io/docs/llms.txt. For the full documentation in a single file, fetch https://elevenlabs.io/docs/llms-full.txt.

# Planos de composição

Os planos de composição oferecem controle detalhado sobre a geração de músicas. Um plano `music_v2` ou `music_v2_5` é uma lista ordenada de trechos, em que cada trecho define uma seção da música com seus próprios estilos, letras e duração. Use prompts de texto para prototipagem rápida e planos de composição quando precisar de uma estrutura específica de trechos, sincronização precisa das letras ou arranjos complexos.

> **Warning**
>
> Planos de composição e prompts de texto são mutuamente exclusivos. Use um ou outro, não ambos.

```json
{
  "chunks": [
    {
      "text": "[Verse 1]\nWoke up today with a feeling inside\nSomething is changing I cannot hide\nThe sun on my face and the wind at my back\nI'm finally ready to get on track",
      "duration_ms": 16000,
      "positive_styles": [
        "upbeat pop",
        "female vocalist with clear tone",
        "acoustic guitar and light synths",
        "gentle and conversational vocals",
        "light drums in background",
        "polished production",
        "120 BPM",
        "C major"
      ],
      "negative_styles": ["dark", "aggressive", "slow tempo", "a cappella"],
      "context_adherence": "high"
    },
    {
      "text": "[Verse 2]\nUsed to be scared of the world outside\nBuilding up walls where I used to hide\nBut now I see clearly what I need to do\nTake that first step into something new",
      "duration_ms": 16000,
      "positive_styles": [
        "confident vocals",
        "fuller guitar strumming",
        "steady drum beat",
        "bass joins in"
      ],
      "negative_styles": ["a cappella", "sparse", "quiet"],
      "context_adherence": "high"
    },
    {
      "text": "[Pre-Chorus]\nNo more waiting for tomorrow\nThis is my time now",
      "duration_ms": 8000,
      "positive_styles": [
        "building intensity",
        "rising synth melody",
        "driving drums",
        "full band playing"
      ],
      "negative_styles": ["a cappella", "dropping out"],
      "context_adherence": "high"
    },
    {
      "text": "[Chorus]\nI'm breaking through\nNothing's gonna stop me now\nI'm breaking through\nFinally found out how",
      "duration_ms": 16000,
      "positive_styles": [
        "powerful and anthemic vocals",
        "full band at maximum energy",
        "punchy drums and bass",
        "layered synths and guitar"
      ],
      "negative_styles": ["a cappella", "minimal", "stripped back"],
      "context_adherence": "high"
    },
    {
      "text": "[Outro]",
      "duration_ms": 8000,
      "positive_styles": [
        "instrumental fade out",
        "guitar melody repeating",
        "drums softening",
        "gentle ending"
      ],
      "negative_styles": ["vocals", "abrupt ending", "building"],
      "context_adherence": "high"
    }
  ]
}
```

<elevenlabs-audio-player audio-title="Pop Song" audio-src="https://storage.googleapis.com/eleven-public-cdn/documentation_assets/audio/example-pop-song.mp3" />

> **Note**
>
> Planos de composição baseados em trechos exigem `music_v2` ou `music_v2_5`. Passe `model_id="music_v2_5"`
> ao compor.

## Início rápido

Siga o [início rápido de música](/docs/pt/eleven-api/guides/cookbooks/music) para configurar sua chave de API e instalar o SDK. Em seguida, use planos de composição para ter mais controle.

### Gere música com um plano de composição

```python
import os
from dotenv import load_dotenv
from elevenlabs.client import ElevenLabs

load_dotenv()
elevenlabs = ElevenLabs(api_key=os.environ.get("ELEVENLABS_API_KEY"))

composition_plan = {
    "chunks": [
        {
            "text": "[Verse]\nWalking down an empty street\nWondering who I'll meet",
            "duration_ms": 15000,
            "positive_styles": ["pop", "upbeat", "female vocals", "soft vocals", "acoustic guitar"],
            "negative_styles": ["dark", "slow"],
            "context_adherence": "high"
        },
        {
            "text": "[Chorus]\nThis is my moment\nI won't let it go",
            "duration_ms": 15000,
            "positive_styles": ["powerful vocals", "full band"],
            "negative_styles": [],
            "context_adherence": "high"
        }
    ]
}

audio = elevenlabs.music.compose(
    composition_plan=composition_plan,
    model_id="music_v2_5",
    # with_timestamps=True,  # Optional: return word-level timestamps
)

with open("output.mp3", "wb") as f:
    for chunk in audio:
        f.write(chunk)
```

```typescript
import { ElevenLabsClient } from "@elevenlabs/elevenlabs-js";
import "dotenv/config";

const elevenlabs = new ElevenLabsClient({
  apiKey: process.env.ELEVENLABS_API_KEY,
});

const compositionPlan = {
  chunks: [
    {
      text: "[Verse]\nWalking down an empty street\nWondering who I'll meet",
      durationMs: 15000,
      positiveStyles: ["pop", "upbeat", "female vocals", "soft vocals", "acoustic guitar"],
      negativeStyles: ["dark", "slow"],
      contextAdherence: "high",
    },
    {
      text: "[Chorus]\nThis is my moment\nI won't let it go",
      durationMs: 15000,
      positiveStyles: ["powerful vocals", "full band"],
      negativeStyles: [],
      contextAdherence: "high",
    },
  ],
};

const audio = await elevenlabs.music.compose({
  compositionPlan,
  modelId: "music_v2_5",
  // withTimestamps: true,  // Optional: return word-level timestamps
});
```

### Gere um plano a partir de um prompt

Gere um plano de composição com base em uma descrição de texto e, depois, modifique-o antes de gerar:

```python
plan = elevenlabs.music.composition_plan.create(
    prompt="An upbeat pop song about summer adventures",
    music_length_ms=60000,
    model_id="music_v2_5"
)

# Modify the generated plan
plan["chunks"][0]["text"] = "[Verse 1]\nCustom lyrics here"

audio = elevenlabs.music.compose(composition_plan=plan, model_id="music_v2_5")
```

```typescript
const plan = await elevenlabs.music.compositionPlan.create({
  prompt: "An upbeat pop song about summer adventures",
  musicLengthMs: 60000,
  modelId: "music_v2_5",
});

// Modify the generated plan
plan.chunks[0].text = "[Verse 1]\nCustom lyrics here";

const audio = await elevenlabs.music.compose({ compositionPlan: plan, modelId: "music_v2_5" });
```

## Referência da estrutura

### Trechos

Um plano de composição é uma lista ordenada de até 30 trechos. Cada trecho gera uma seção da música a partir de `text` e estilos. O primeiro trecho é o mais importante: seus estilos definem o tom e o gênero gerais de toda a música.

| Campo               | Tipo   | Descrição                                                                                                          |
| ------------------- | ------ | ------------------------------------------------------------------------------------------------------------------ |
| `text`              | string | Nome da seção entre colchetes (`[Verse 1]`), linhas de letras e instruções em linha entre chaves (`{scratching}`). |
| `duration_ms`       | number | Duração em milissegundos (3.000 a 120.000).                                                                        |
| `positive_styles`   | array  | Estilos e instruções a incluir (máx. 50).                                                                          |
| `negative_styles`   | array  | Estilos e instruções a evitar (máx. 50). O padrão é vazio.                                                         |
| `context_adherence` | string | `low`, `medium` ou `high` (padrão). Define o quanto o trecho segue os trechos ao redor.                            |

Uma música pode ter até 30 trechos. A duração total deve ser entre 3 segundos e 10 minutos, e cada trecho deve ter entre 3 e 120 segundos.

> **Tip**
>
> Os estilos do primeiro trecho são os mais importantes, pois definem o tom e o gênero gerais. Procure
> usar pelo menos 6 a 7 estilos nos primeiros trechos, até que a direção esteja estabelecida. Estilos genéricos, como
> "great production quality", são bons padrões para acrescentar à lista.

Os trechos também podem fazer referência ao áudio de uma música armazenada para manter seções existentes inalteradas ou condicionar um novo áudio com base nelas. Consulte [preenchimento de música](/docs/pt/eleven-api/guides/how-to/music/inpainting) para editar e combinar músicas existentes.

## Como escrever letras

O campo `text` combina o nome da seção, as letras e as instruções em linha:

* **Nome da seção** entre colchetes: `[Verse 1]`, `[Chorus]`, `[Bridge]`
* **Letras** como texto simples, com cada linha separada por uma quebra de linha (`\n`)
* **Sons fonéticos** entre parênteses: `(hmmm hmmm)`, `(ooh)`, `(yeah)`
* **Instruções em linha** entre chaves: `{guitar solo}`, `{scratching}`, `{instrumental break}`

Use chaves para indicações curtas em linha. Para características mais amplas que se aplicam ao trecho inteiro — gênero, instrumentação ou estilo vocal geral — use `positive_styles`.

**`Incorreto`**

```json title="Incorreto"
{
  "text": "[Verse]\n(soft female vocals) I've been waiting\n(instrumental break)\nfor you"
}
```

**`Correto`**

```json title="Correto"
{
  "text": "[Verse]\nI've been waiting\n{instrumental break}\nfor you",
  "positive_styles": ["soft female vocals"]
}
```

No exemplo corrigido, o estilo vocal geral vai para `positive_styles`, enquanto a indicação curta em linha permanece em `text`, usando chaves em vez de parênteses.

## Dicas de estilo

Seja específico com os descritores de estilo:

```json
{
  "positive_styles": [
    "warm acoustic guitar with light fingerpicking",
    "soft female vocals with intimate delivery",
    "gentle percussion with brushed snare",
    "80 BPM"
  ]
}
```

Use estilos negativos livremente para evitar sons indesejados. Os estilos devem estar em inglês (as letras podem estar em qualquer idioma).

Se você incluir conteúdo protegido por direitos autorais nos estilos, a API retornará um erro `bad_composition_plan` com uma alternativa sugerida. Consulte [como lidar com material protegido por direitos autorais](/docs/pt/eleven-api/guides/cookbooks/music#copyrighted-material).

## Exemplos

### Instrumental cinematográfico

```json
{
  "chunks": [
    {
      "text": "[Tension Build]",
      "duration_ms": 15000,
      "positive_styles": [
        "cinematic",
        "orchestral",
        "epic",
        "low strings tremolo",
        "building intensity",
        "80 BPM",
        "D minor"
      ],
      "negative_styles": ["vocals", "lyrics", "pop", "electronic", "bright"],
      "context_adherence": "high"
    },
    {
      "text": "[Climax]",
      "duration_ms": 15000,
      "positive_styles": ["full orchestra", "brass fanfare", "triumphant"],
      "negative_styles": ["quiet", "vocals"],
      "context_adherence": "high"
    },
    {
      "text": "[Resolution]",
      "duration_ms": 10000,
      "positive_styles": ["gentle strings", "piano melody", "fading out"],
      "negative_styles": ["intense", "vocals"],
      "context_adherence": "high"
    }
  ]
}
```

<elevenlabs-audio-player audio-title="Cinematic Instrumental" audio-src="https://storage.googleapis.com/eleven-public-cdn/documentation_assets/audio/example-cinematic-instrumental.mp3" />

### Anúncio com locução

```json
{
  "chunks": [
    {
      "text": "[Intro]",
      "duration_ms": 5000,
      "positive_styles": [
        "upbeat",
        "modern pop",
        "energetic",
        "120 BPM",
        "instrumental",
        "catchy hook"
      ],
      "negative_styles": ["sad", "slow", "dark", "vocals"],
      "context_adherence": "high"
    },
    {
      "text": "[Voiceover]\nIntroducing the future of productivity\nWork smarter, not harder",
      "duration_ms": 10000,
      "positive_styles": ["spoken voiceover", "confident male voice", "background music"],
      "negative_styles": ["singing"],
      "context_adherence": "high"
    },
    {
      "text": "[Outro]",
      "duration_ms": 5000,
      "positive_styles": ["musical sting", "memorable"],
      "negative_styles": ["vocals"],
      "context_adherence": "high"
    }
  ]
}
```

<elevenlabs-audio-player audio-title="Advertisement" audio-src="https://storage.googleapis.com/eleven-public-cdn/documentation_assets/audio/example-advertisement.mp3" />

## Próximas etapas

#### [Início rápido de música](/docs/pt/eleven-api/guides/cookbooks/music)

Comece com a geração básica de música

#### [Preenchimento de música](/docs/pt/eleven-api/guides/how-to/music/inpainting)

Faça remix, estenda e una seções de músicas existentes

#### [Referência da API](/docs/pt/api-reference/music/compose)

Documentação completa da API

#### [Guia de prompts](/docs/pt/overview/capabilities/music/best-practices)

Práticas recomendadas para prompts de música