> 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/text-to-dialogue
Content-Type: application/json

将文本和音色 ID 对列表转换为语音（对话），并返回音频。

Reference: https://elevenlabs.io/docs/api-reference/text-to-dialogue/convert

## 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: mp3_44100_128) — 生成音频的输出格式。格式为 codec_sample_rate_bitrate。因此，采样率为 22.05kHz、比特率为 32kbs 的 mp3 表示为 mp3_22050_32。使用 192kbps 比特率的 MP3 需要订阅 Creator 或更高版本。采样率为 44.1kHz 的 PCM 和 WAV 格式需要订阅 Pro 或更高版本。请注意，μ-law 格式（有时写作 mu-law，通常近似写作 u-law）常用于 Twilio 音频输入。
  - Allowed values: `alaw_8000`, `mp3_22050_32`, `mp3_24000_48`, `mp3_44100_128`, `mp3_44100_192`, `mp3_44100_32`, `mp3_44100_64`, `mp3_44100_96`, `opus_48000_128`, `opus_48000_192`, `opus_48000_32`, `opus_48000_64`, `opus_48000_96`, `pcm_16000`, `pcm_22050`, `pcm_24000`, `pcm_32000`, `pcm_44100`, `pcm_48000`, `pcm_8000`, `ulaw_8000`, `wav_16000`, `wav_22050`, `wav_24000`, `wav_32000`, `wav_44100`, `wav_48000`, `wav_8000`
- `enable_logging` (boolean, optional, default: true) — 当 enable_logging 设为 false 时，此请求将使用零留存模式。这意味着该请求无法使用历史记录功能，包括请求拼接。零留存模式仅限企业版客户使用。

### Body (application/json)

This endpoint expects a Body_Text_to_dialogue__multi_voice__v1_text_to_dialogue_post.

- `inputs` (list of DialogueInput, required) — 对话输入列表，每项包含将转换为语音的文本和音色 ID。唯一音色 ID 最多为 10 个。为确保生成稳定，每次请求中所有 `inputs[].text` 值的总字符数应不超过 2,000 个字符。较长的请求可能在流式响应中提前终止，或返回验证错误。
- `model_id` (string, optional, default: eleven_v3) — 要使用的模型标识符，可通过 GET /v1/models 查询。模型必须支持文本转语音，可通过 can_do_text_to_speech 属性确认。
- `language_code` (string, optional, nullable) — 用于为模型和文本规范化强制指定语言的语言代码（ISO 639-1）。如果模型不支持提供的语言代码，将忽略该代码。multilingual_v2 模型不支持此参数。
- `settings` (ToDialogueSettingsResponseModel, optional, nullable) — 控制对话生成的设置。
- `previous_text` (string, optional, nullable) — 紧接在此次生成之前的文本，用于让模型保持韵律连贯性。最多可发送 100 个字符。并非所有模型均支持。
- `future_text` (string, optional, nullable) — 紧接在此次生成之后的文本，用于让模型保持韵律连贯性。最多可发送 100 个字符。并非所有模型均支持。
- `pronunciation_dictionary_locators` (list of PronunciationDictionaryVersionLocatorRequestModel, optional, nullable) — 要应用于文本的发音词典定位符（id、version_id）列表。将按顺序应用。每次请求最多可包含 3 个定位符。
- `seed` (integer, optional, nullable) — 指定后，系统会尽力进行确定性采样，使使用相同种子和参数的重复请求返回相同结果。但不保证完全确定。必须是介于 0 和 4294967295 之间的整数。
- `apply_text_normalization` (enum, optional, default: auto) — 此参数通过 3 种模式控制文本规范化：'auto'、'on' 和 'off'。设为 'auto' 时，系统会自动决定是否应用文本规范化（如将数字读出）。设为 'on' 时始终应用；设为 'off' 时跳过。
  - Allowed values: `auto`, `on`, `off`
- `previous_request_ids` (list of string, optional, nullable) — 本次对话生成之前的 request_ids 列表。将大型任务拆分为多个请求时，用于让模型保持连贯性。最多可发送 3 个 request_ids。最后一个 request_id 对应的音频最接近当前请求。并非所有模型都支持此功能。
- `next_request_ids` (list of string, optional, nullable) — 本次对话生成之后的 request_ids 列表。重新生成序列中间的片段时，可用于保持连贯性。最多可发送 3 个 request_ids。第一个 request_id 对应的音频最接近当前请求。并非所有模型都支持此功能。
- `audio_effects` (EffectsSpec-Input, optional, nullable) — 应用于生成音频的音效。未知 ID 会返回 404，`param` 会指明相应字段。混响（`environment_id` 的 `send_level` 大于 0）和非零 `pan` 会生成立体声音频，因此 `ulaw_*`、`alaw_*` 和 `pcm_*` 输出格式会返回 400。音效不会改变请求费用。
- `use_pvc_as_ivc` (boolean, optional, nullable, deprecated) — 是否使用专业音色的 IVC 版本。这可能提升表现力并降低延迟。

## Response

### 200

生成的音频文件

- File download.

## Errors

### 422 Unprocessable Entity Error

验证错误。

- `detail` (list of ValidationError, optional)

## Types

### DialogueInput

- `text` (string, required) — 要转换为语音的文本。
- `voice_id` (string, required) — 生成时使用的音色 ID。

### ToDialogueSettingsResponseModel

- `stability` (double, optional, nullable, default: 0.5) — 决定音色的稳定性以及每次生成之间的随机性。较低的值会带来更丰富的情感范围。较高的值可能使音色较为单调，情感有限。
- `similarity` (double, optional, nullable, default: 0.75) — 决定生成过程中对模型的引导强度。较高的值会让模型更贴近音色，但会减少变化性。并非所有模型都支持。
- `clone_strength` (double, optional, nullable) — 控制音色与专业语音克隆样本的匹配程度，范围为 0（低）到 1（高）。大多数情况下建议设为 0。仅当默认设置出现问题时才提高此值。仅适用于为所选 v4 模型微调的专业语音克隆。

### PronunciationDictionaryVersionLocatorRequestModel

- `pronunciation_dictionary_id` (string, required) — 发音词典的 ID。
- `version_id` (string, optional, nullable) — 发音词典版本的 ID。未提供时，将使用最新版本。

### EffectsSpec-Input

应用于生成语音的音频效果：滤镜预设、感知距离、混响 环境、背景噪声底音和立体声声像。将所有字段保留为默认值， 即可获得未经处理的音频。

- `filter_preset_id` (string, optional, nullable) — 为语音增添音色特征的滤镜预设 ID，例如 `phone` 或 `old_radio`。使用 `GET /v1/audio-effects/catalog` 列出有效 ID。
- `distance` (double, optional, default: 0) — 说话者听起来与麦克风的距离，范围为 0（近，不变）至 1（远）。值越高，低频和高频衰减越多；设置环境后，干声与混响之间的平衡会更偏向混响。
- `environment_id` (string, optional, nullable) — 将语音置于特定空间中的混响环境 ID，例如 `small_room` 或 `hall`。使用 `GET /v1/audio-effects/catalog` 列出有效 ID。混响以立体声渲染，并会在语音结束后添加最长数秒的余响。
- `background_noise_id` (string, optional, nullable) — 在语音下方循环播放的背景噪声底音 ID，例如 `cafe` 或 `keyboard`。使用 `GET /v1/audio-effects/catalog` 列出有效 ID。
- `send_level` (double, optional, default: 1) — 输入混响的语音比例，范围为 0（无）至 1（全部）。仅在设置 `environment_id` 时生效；0 会关闭混响。
- `pan` (double, optional, default: 0) — 音色的立体声位置，范围从 -1（最左）经 0（居中）到 1（最右）。仅音色会进行声像定位；混响和背景噪声保持居中。

### ValidationError

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

### ValidationErrorLocItems

- string
- integer

## Examples

**Request**

```json
{
  "inputs": [
    {
      "text": "[giggling] Knock knock",
      "voice_id": "JBFqnCBsd6RMkjVDRZzb"
    },
    {
      "text": "[curious] Who is there?",
      "voice_id": "Aw4FAjKCGjjNkVhN1Xmq"
    }
  ]
}
```

**SDK Code**

```python
import requests

url = "https://api.elevenlabs.io/v1/text-to-dialogue"

payload = { "inputs": [
        {
            "text": "[giggling] Knock knock",
            "voice_id": "JBFqnCBsd6RMkjVDRZzb"
        },
        {
            "text": "[curious] Who is there?",
            "voice_id": "Aw4FAjKCGjjNkVhN1Xmq"
        }
    ] }
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/text-to-dialogue';
const options = {
  method: 'POST',
  headers: {'xi-api-key': 'xi-api-key', 'Content-Type': 'application/json'},
  body: '{"inputs":[{"text":"[giggling] Knock knock","voice_id":"JBFqnCBsd6RMkjVDRZzb"},{"text":"[curious] Who is there?","voice_id":"Aw4FAjKCGjjNkVhN1Xmq"}]}'
};

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/text-to-dialogue"

	payload := strings.NewReader("{\n  \"inputs\": [\n    {\n      \"text\": \"[giggling] Knock knock\",\n      \"voice_id\": \"JBFqnCBsd6RMkjVDRZzb\"\n    },\n    {\n      \"text\": \"[curious] Who is there?\",\n      \"voice_id\": \"Aw4FAjKCGjjNkVhN1Xmq\"\n    }\n  ]\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/text-to-dialogue")

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  \"inputs\": [\n    {\n      \"text\": \"[giggling] Knock knock\",\n      \"voice_id\": \"JBFqnCBsd6RMkjVDRZzb\"\n    },\n    {\n      \"text\": \"[curious] Who is there?\",\n      \"voice_id\": \"Aw4FAjKCGjjNkVhN1Xmq\"\n    }\n  ]\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/text-to-dialogue")
  .header("xi-api-key", "xi-api-key")
  .header("Content-Type", "application/json")
  .body("{\n  \"inputs\": [\n    {\n      \"text\": \"[giggling] Knock knock\",\n      \"voice_id\": \"JBFqnCBsd6RMkjVDRZzb\"\n    },\n    {\n      \"text\": \"[curious] Who is there?\",\n      \"voice_id\": \"Aw4FAjKCGjjNkVhN1Xmq\"\n    }\n  ]\n}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.elevenlabs.io/v1/text-to-dialogue', [
  'body' => '{
  "inputs": [
    {
      "text": "[giggling] Knock knock",
      "voice_id": "JBFqnCBsd6RMkjVDRZzb"
    },
    {
      "text": "[curious] Who is there?",
      "voice_id": "Aw4FAjKCGjjNkVhN1Xmq"
    }
  ]
}',
  '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/text-to-dialogue");
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  \"inputs\": [\n    {\n      \"text\": \"[giggling] Knock knock\",\n      \"voice_id\": \"JBFqnCBsd6RMkjVDRZzb\"\n    },\n    {\n      \"text\": \"[curious] Who is there?\",\n      \"voice_id\": \"Aw4FAjKCGjjNkVhN1Xmq\"\n    }\n  ]\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 = ["inputs": [
    [
      "text": "[giggling] Knock knock",
      "voice_id": "JBFqnCBsd6RMkjVDRZzb"
    ],
    [
      "text": "[curious] Who is there?",
      "voice_id": "Aw4FAjKCGjjNkVhN1Xmq"
    ]
  ]] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api.elevenlabs.io/v1/text-to-dialogue")! 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()
```