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

# 创作音乐并返回详细响应

POST https://api.elevenlabs.io/v1/music/detailed
Content-Type: application/json

Compose a song from a prompt or a composition plan.

Reference: https://elevenlabs.io/docs/api-reference/music/compose-detailed

## Servers

- `https://api.elevenlabs.io` (Production, default)
- `https://api.us.elevenlabs.io` (Production US)
- `https://api.eu.residency.elevenlabs.io` (Production EU)
- `https://api.in.residency.elevenlabs.io` (Production India)
- `https://api.sg.residency.elevenlabs.io` (Production Singapore)

## Request

### Query parameters

- `output_format` (enum, optional, default: auto) — 生成音频的输出格式。格式为 codec_sample_rate_bitrate。使用 "auto"（默认值）可让 API 为所选模型选择最佳格式：v1 模型使用 mp3_44100_128，v2 模型使用 mp3_48000_192。
  - Allowed values: `auto`, `mp3_48000_128`, `mp3_48000_192`, `mp3_48000_240`, `mp3_48000_320`, `mp3_22050_32`, `mp3_24000_48`, `mp3_44100_32`, `mp3_44100_64`, `mp3_44100_96`, `mp3_44100_128`, `mp3_44100_192`, `pcm_8000`, `pcm_16000`, `pcm_22050`, `pcm_24000`, `pcm_32000`, `pcm_44100`, `pcm_48000`, `ulaw_8000`, `alaw_8000`, `opus_48000_32`, `opus_48000_64`, `opus_48000_96`, `opus_48000_128`, `opus_48000_192`
- `enable_logging` (boolean, optional, default: true) — 当 enable_logging 设为 false 时，该请求将使用零保留模式。零保留模式仅限企业版客户使用。

### Body (application/json)

This endpoint expects a Body_Compose_Music_with_a_detailed_response_v1_music_detailed_post.

- `prompt` (string, optional, nullable) — 用于生成歌曲的简单文本提示词。不能与 `composition_plan` 一起使用。
- `composition_plan` (BodyComposeMusicWithADetailedResponseV1MusicDetailedPostCompositionPlan, optional, nullable) — 用于指导音乐生成的详细作曲计划。不能与 `prompt` 一起使用。
- `music_length_ms` (integer, optional, nullable) — 要生成的歌曲长度，单位为 ms。仅可与 `prompt` 一起使用。必须介于 3000ms 和 600000ms 之间。可选；未提供时，模型将根据提示词选择长度。
- `model_id` (enum, optional, default: music_v1) — 用于生成的模型。
  - Allowed values: `music_v1`, `music_v2`, `music_v2_5`
- `seed` (integer, optional, nullable) — 用于初始化音乐生成过程的随机种子。使用相同参数提供相同种子有助于获得更一致的结果，但不保证完全可复现，输出可能会随系统更新而变化。不可与 prompt 同时使用。
- `force_instrumental` (boolean, optional, default: false) — 如果为 true，确保生成的歌曲为纯音乐。如果为 false，歌曲是否为纯音乐取决于 `prompt`。只能与 `prompt` 一起使用。
- `finetune_id` (string, optional, nullable) — 用于生成的 Finetune ID
- `respect_sections_durations` (boolean, optional, default: true) — 控制是否严格执行 `composition_plan` 中各段的时长。仅与 `composition_plan` 配合使用，且仅适用于 `music_v1`；对于 `music_v2` 和 `music_v2_5`，始终会执行分段时长，此设置将被忽略。对于 `music_v1`，当值为 false 时，模型可能会调整各段时长，以改善质量和延迟，同时保持计划中的歌曲总时长。
- `store_for_inpainting` (boolean, optional, default: false) — 是否存储生成的歌曲以供局部重绘。
- `with_timestamps` (boolean, optional, default: false) — 是否返回生成歌曲中各单词的时间戳。
- `with_waveform_visual` (boolean, optional, default: false) — 是否返回生成歌曲的可视化波形。
- `sign_with_c2pa` (boolean, optional, default: false) — 是否使用 C2PA 为生成的歌曲签名。仅适用于 mp3 文件。

## Response

### 200

包含 JSON 元数据和二进制音频文件的 multipart/mixed 响应

## Errors

### 422 Unprocessable Entity Error

验证错误。

- `detail` (list of ValidationError, optional)

## Types

### BodyComposeMusicWithADetailedResponseV1MusicDetailedPostCompositionPlan

用于指导音乐生成的详细作曲计划。不能与 `prompt` 一起使用。

- MusicPrompt: MusicPrompt
- CompositionPlan: CompositionPlan

### ValidationError

- `loc` (list of ValidationErrorLocItems, required)
- `msg` (string, required)
- `type` (string, required)

### MusicPrompt

Composition plan for the `music_v1` model. Using this field with any other model will result in an error.

- `positive_global_styles` (list of string, required) — 整首歌曲应包含的风格和音乐方向。使用英文效果最佳。
- `negative_global_styles` (list of string, required) — 整首歌曲不应包含的风格和音乐方向。使用英文效果最佳。
- `sections` (list of SongSection, required) — 歌曲的段落。

### CompositionPlan

Composition plan for the `music_v2` and `music_v2_5` models. Using this field with any other model will result in an error.

- `chunks` (list of CompositionPlanChunksItems, required) — 构成该生成内容的分块。

### ValidationErrorLocItems

- string
- integer

### SongSection

- `section_name` (string, required) — 章节名称。必须包含 1 至 100 个字符。
- `positive_local_styles` (list of string, required) — 此段落应包含的风格和音乐方向。使用英文效果最佳。
- `negative_local_styles` (list of string, required) — 此部分不应包含的风格和音乐指示。使用英语效果最佳。
- `duration_ms` (integer, required) — 片段时长，单位为 ms。必须介于 3000ms 到 120000ms 之间。
- `lines` (list of string, required) — 该段的歌词。每段最多 30 行，每行最多 200 个字符。
- `source_from` (SectionSource, optional, nullable) — 用于提取片段的可选源。用于局部重绘。

### CompositionPlanChunksItems

- GenerationChunk: GenerationChunk-Input
- AudioRefChunk: AudioRefChunk

### SectionSource

- `song_id` (string, required) — 要从中获取段落的歌曲 ID。生成歌曲时，可在响应标头中找到歌曲 ID。
- `range` (TimeRange, required) — 从源歌曲中提取的范围。
- `negative_ranges` (list of TimeRange, optional) — 从 'range' 中排除的范围。

### GenerationChunk-Input

- `text` (string, required) — 要为此片段生成的文本配置。开头可包含方括号中的可选段落名称，例如 \[Verse 1]、歌词行，以及花括号中的内联指示，例如 \{scratching}。段落名称须为 1 至 100 个字符。最多允许 30 行，每行最多 200 个字符。
- `duration_ms` (integer, required) — 分块时长，单位为 ms。必须介于 3000ms 到 120000ms 之间。
- `positive_styles` (list of string, required) — 此片段应包含的风格和音乐方向。使用英文效果最佳。首个片段的风格最重要，因为它决定整体基调和流派。后续片段的风格可用于增加细微变化、推进、强调，或改变歌曲方向。在方向确定前，建议早期片段至少包含 6-7 种风格。可在列表中追加如 'great production quality' 等通用风格，作为良好的默认设置。
- `negative_styles` (list of string, optional) — 此片段不应包含的风格和音乐方向。使用英文效果最佳。留空是合适的默认设置；仅当你想明确避免特定风格或方向时才使用此字段。
- `context_adherence` (enum, optional, default: high) — 模型遵循周围分块上下文的程度。较低遵循度意味着模型可偏离上下文并更具创造性。较高遵循度意味着模型会更符合上下文。
  - Allowed values: `low`, `medium`, `high`
- `conditioning_ref` (AudioRefChunk, optional, nullable) — 用于条件生成的音频参考。第一个分块最重要，因为它会影响后续所有分块的生成。因此，如需对整首歌曲应用条件控制，请从第一个分块开始。
- `condition_strength` (enum, optional, nullable) — 模型遵循条件参考的强度。较低强度意味着模型会更具创造性并偏离参考；较高强度意味着模型会更符合参考。
  - Allowed values: `low`, `medium`, `high`, `xhigh`

### AudioRefChunk

- `song_id` (string, required) — 要从中获取片段的歌曲 ID。生成歌曲时，可在响应标头中找到歌曲 ID。
- `range` (TimeRange, required) — 要从歌曲中提取的时间范围。

### TimeRange

- `start_ms` (integer, required)
- `end_ms` (integer, required)

## Examples

**Request**

```json
{
  "prompt": "A prompt for music generation",
  "music_length_ms": 10000
}
```

**Response**

```json
{
  "audio": "[binary audio data]",
  "composition_plan": {
    "negative_global_styles": [
      "metal",
      "hip-hop",
      "country"
    ],
    "positive_global_styles": [
      "pop",
      "rock",
      "jazz"
    ],
    "sections": [
      {
        "duration_ms": 10000,
        "lines": [
          "Verse 1 lyrics"
        ],
        "negative_local_styles": [
          "metal",
          "hip-hop",
          "country"
        ],
        "positive_local_styles": [
          "pop",
          "rock",
          "jazz"
        ],
        "section_name": "Verse 1"
      }
    ]
  },
  "song_metadata": {
    "description": "我的歌曲描述",
    "genres": [
      "pop",
      "rock",
      "jazz"
    ],
    "is_explicit": false,
    "languages": [
      "en",
      "fr"
    ],
    "title": "My Song"
  }
}
```

**SDK Code**

```python
import requests

url = "https://api.elevenlabs.io/v1/music/detailed"

payload = {
    "prompt": "A prompt for music generation",
    "music_length_ms": 10000
}
headers = {
    "xi-api-key": "xi-api-key",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://api.elevenlabs.io/v1/music/detailed';
const options = {
  method: 'POST',
  headers: {'xi-api-key': 'xi-api-key', 'Content-Type': 'application/json'},
  body: '{"prompt":"A prompt for music generation","music_length_ms":10000}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.elevenlabs.io/v1/music/detailed"

	payload := strings.NewReader("{\n  \"prompt\": \"A prompt for music generation\",\n  \"music_length_ms\": 10000\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("xi-api-key", "xi-api-key")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://api.elevenlabs.io/v1/music/detailed")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["xi-api-key"] = 'xi-api-key'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"prompt\": \"A prompt for music generation\",\n  \"music_length_ms\": 10000\n}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.elevenlabs.io/v1/music/detailed")
  .header("xi-api-key", "xi-api-key")
  .header("Content-Type", "application/json")
  .body("{\n  \"prompt\": \"A prompt for music generation\",\n  \"music_length_ms\": 10000\n}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.elevenlabs.io/v1/music/detailed', [
  'body' => '{
  "prompt": "A prompt for music generation",
  "music_length_ms": 10000
}',
  'headers' => [
    'Content-Type' => 'application/json',
    'xi-api-key' => 'xi-api-key',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://api.elevenlabs.io/v1/music/detailed");
var request = new RestRequest(Method.POST);
request.AddHeader("xi-api-key", "xi-api-key");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"prompt\": \"A prompt for music generation\",\n  \"music_length_ms\": 10000\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "xi-api-key": "xi-api-key",
  "Content-Type": "application/json"
]
let parameters = [
  "prompt": "A prompt for music generation",
  "music_length_ms": 10000
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.elevenlabs.io/v1/music/detailed")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```