> 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/upload
Content-Type: multipart/form-data

上传音乐文件以供后续局部重绘使用。上传价格与生成歌曲相同。所有上传内容都会接受版权侵权检查。如检测到受版权保护的内容，仍将收取请求费用的一半。

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

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

### Body (multipart/form-data)

This endpoint expects a multipart form containing a file.

- `file` (file, required) — 要上传的音频文件。
- `extract_composition_plan` (V1MusicUploadPostRequestBodyContentMultipartFormDataSchemaExtractCompositionPlan, optional) — 是否为上传的歌曲生成并返回创作计划。传入模型 ID（`music_v1`、`music_v2` 或 `music_v2_5`）可控制返回的创作计划格式。传入 `true`/`false` 已弃用；`true` 默认使用 `music_v1` 计划格式。启用此项会增加延迟。
- `with_timestamps` (boolean, optional) — 是否转录上传的歌曲并返回单词级时间戳。如果为 True，响应将包含 words_timestamps，但会增加延迟。
- `with_waveform_visual` (boolean, optional) — 是否返回上传歌曲的可视化波形。

## Response

### 200

已成功上传音乐文件及可选作曲计划

- `song_id` (string, required) — 上传歌曲的唯一标识符。
- `composition_plan` (MusicUploadResponseCompositionPlan, optional, nullable) — 从上传歌曲中提取的作曲方案。仅当请求正文中提供了 `extract_composition_plan` 时出现。
- `words_timestamps` (list of WordTimestamp, optional, nullable) — 从上传歌曲转录的单词级时间戳。仅当请求体中的 `with_timestamps` 为 True 时提供。
- `waveform_visual` (list of integer, optional, nullable) — 上传歌曲的低分辨率波形，用于显示预览。每秒音频包含 4 个值，范围为 -1000 至 1000。立体声会混合为单声道。仅当请求正文中的 `with_waveform_visual` 为 True 时提供。

## Errors

### 422 Unprocessable Entity Error

验证错误。

- `detail` (list of ValidationError, optional)

## Types

### MusicUploadResponseCompositionPlan

从上传歌曲中提取的作曲方案。仅当请求正文中提供了 `extract_composition_plan` 时出现。

- MusicPrompt: MusicPrompt
- CompositionPlan: CompositionPlan

### WordTimestamp

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

### 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
{
  "file": "<file: string>"
}
```

**Response**

```json
{
  "song_id": "jR4Xz8kL2mNpQ9wVtY1b"
}
```

**SDK Code**

```python
import requests

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

files = { "file": "open('string', 'rb')" }
payload = {
    "extract_composition_plan": ,
    "with_timestamps": ,
    "with_waveform_visual": 
}

response = requests.post(url, data=payload, files=files)

print(response.json())
```

```javascript
const url = 'https://api.elevenlabs.io/v1/music/upload';
const form = new FormData();
form.append('extract_composition_plan', '');
form.append('file', 'string');
form.append('with_timestamps', '');
form.append('with_waveform_visual', '');

const options = {method: 'POST'};

options.body = form;

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/upload"

	payload := strings.NewReader("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"extract_composition_plan\"\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"string\"\r\nContent-Type: application/octet-stream\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"with_timestamps\"\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"with_waveform_visual\"\r\n\r\n\r\n-----011000010111000001101001--\r\n")

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

	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/upload")

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

request = Net::HTTP::Post.new(url)
request.body = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"extract_composition_plan\"\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"string\"\r\nContent-Type: application/octet-stream\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"with_timestamps\"\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"with_waveform_visual\"\r\n\r\n\r\n-----011000010111000001101001--\r\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/upload")
  .body("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"extract_composition_plan\"\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"string\"\r\nContent-Type: application/octet-stream\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"with_timestamps\"\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"with_waveform_visual\"\r\n\r\n\r\n-----011000010111000001101001--\r\n")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.elevenlabs.io/v1/music/upload', [
  'multipart' => [
    [
        'name' => 'file',
        'filename' => 'string',
        'contents' => null
    ]
  ]
]);

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

```csharp
using RestSharp;

var client = new RestClient("https://api.elevenlabs.io/v1/music/upload");
var request = new RestRequest(Method.POST);
request.AddParameter("undefined", "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"extract_composition_plan\"\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"string\"\r\nContent-Type: application/octet-stream\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"with_timestamps\"\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"with_waveform_visual\"\r\n\r\n\r\n-----011000010111000001101001--\r\n", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation
let parameters = [
  [
    "name": "extract_composition_plan",
    "value": 
  ],
  [
    "name": "file",
    "fileName": "string"
  ],
  [
    "name": "with_timestamps",
    "value": 
  ],
  [
    "name": "with_waveform_visual",
    "value": 
  ]
]

let boundary = "---011000010111000001101001"

var body = ""
var error: NSError? = nil
for param in parameters {
  let paramName = param["name"]!
  body += "--\(boundary)\r\n"
  body += "Content-Disposition:form-data; name=\"\(paramName)\""
  if let filename = param["fileName"] {
    let contentType = param["content-type"]!
    let fileContent = String(contentsOfFile: filename, encoding: String.Encoding.utf8)
    if (error != nil) {
      print(error as Any)
    }
    body += "; filename=\"\(filename)\"\r\n"
    body += "Content-Type: \(contentType)\r\n\r\n"
    body += fileContent
  } else if let paramValue = param["value"] {
    body += "\r\n\r\n\(paramValue)"
  }
}

let request = NSMutableURLRequest(url: NSURL(string: "https://api.elevenlabs.io/v1/music/upload")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
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()
```