> 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-speech/{voice_id}/stream
Content-Type: application/json

使用所选音色将文本转换为语音，并以音频流形式返回。

Reference: https://elevenlabs.io/docs/api-reference/text-to-speech/stream

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

### Path parameters

- `voice_id` (string, required) — 要使用的音色 ID。使用 [获取音色](/docs/api-reference/voices/search) 端点列出所有可用音色。

### Query parameters

- `enable_logging` (boolean, optional, default: true) — 当 enable_logging 设为 false 时，此请求将使用零留存模式。这意味着该请求无法使用历史记录功能，包括请求拼接。零留存模式仅限企业版客户使用。
- `optimize_streaming_latency` (integer, optional, nullable, deprecated) — 可启用延迟优化，但会牺牲部分质量。可达到的最低最终延迟因模型而异。可选值： 0 - 默认模式（不进行延迟优化） 1 - 常规延迟优化（约为选项 3 可实现延迟改善的 50%） 2 - 强延迟优化（约为选项 3 可实现延迟改善的 75%） 3 - 最大延迟优化 4 - 最大延迟优化，同时关闭文本规范化以进一步降低延迟（延迟最低，但可能会错误朗读数字、日期等）。 默认值为 None。
- `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 格式需要订阅 Pro 或更高版本。请注意，μ-law 格式（有时写作 mu-law，通常近似写作 u-law）常用于 Twilio 音频输入。
  - Allowed values: `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`

### Body (application/json)

This endpoint expects a Body_text_to_speech_stream.

- `text` (string, required) — 将转换为语音的文本。
- `model_id` (string, optional, default: eleven_multilingual_v2) — 要使用的模型标识符，可通过 GET /v1/models 查询。模型必须支持文本转语音，可通过 can_do_text_to_speech 属性确认。
- `language_code` (string, optional, nullable) — 用于为模型和文本规范化强制指定语言的语言代码（ISO 639-1）。如果模型不支持提供的语言代码，将忽略该代码。multilingual_v2 模型不支持此参数。
- `voice_settings` (VoiceSettingsResponseModel, optional, nullable) — 覆盖指定音色已存储设置的音色设置，仅应用于当前请求。
- `pronunciation_dictionary_locators` (list of PronunciationDictionaryVersionLocatorRequestModel, optional, nullable) — 要应用于文本的发音词典定位符（id、version_id）列表。将按顺序应用。每次请求最多可包含 3 个定位符。
- `seed` (integer, optional, nullable) — 指定后，系统会尽力进行确定性采样，使使用相同种子和参数的重复请求返回相同结果。但不保证完全确定。必须是介于 0 和 4294967295 之间的整数。
- `previous_text` (string, optional, nullable) — 当前请求文本之前的文本。可用于提升拼接多个生成结果时的语音连贯性，或影响当前生成的语音连贯性。
- `next_text` (string, optional, nullable) — 当前请求文本之后的文本。可用于提升拼接多个生成结果时的语音连贯性，或影响当前生成的语音连贯性。
- `previous_request_ids` (list of string, optional, nullable) — 本次生成之前样本的 request_id 列表。将大型任务拆分为多个请求时，可用于提升语音连贯性。所有生成使用同一模型时效果最佳。如果同时发送 previous_text 和 previous_request_ids，将忽略 previous_text。最多可发送 3 个 request_ids。
- `next_request_ids` (list of string, optional, nullable) — 本次生成后续样本的 request_id 列表。重新生成存在音频质量问题的样本时，next_request_ids 对保持语音连贯性尤其有用。例如，已生成 3 个语音片段且想改善第 2 段时，将第 3 段的请求 ID 作为 next_request_id（第 1 段的请求 ID 作为 previous_request_id）传入，有助于保持合并后语音的自然流畅。所有生成使用同一模型时效果最佳。如果同时发送 next_text 和 next_request_ids，将忽略 next_text。最多可发送 3 个 request_ids。
- `use_pvc_as_ivc` (boolean, optional, nullable) — 是否使用专业音色的 IVC 版本。这可能提升表现力并降低延迟。
- `apply_text_normalization` (enum, optional, default: auto) — 此参数通过 3 种模式控制文本规范化：'auto'、'on' 和 'off'。设为 'auto' 时，系统会自动决定是否应用文本规范化（如将数字读出）。设为 'on' 时始终应用；设为 'off' 时跳过。
  - Allowed values: `auto`, `on`, `off`
- `apply_language_text_normalization` (boolean, optional, default: false) — 此参数控制语言文本规范化，有助于部分支持语言中的文本正确发音。警告：此参数可能大幅增加请求延迟。目前仅支持日语。
- `audio_effects` (EffectsSpec-Input, optional, nullable) — 应用于生成音频的音效。未知 ID 会返回 404，`param` 会指明相应字段。混响（`environment_id` 的 `send_level` 大于 0）和非零 `pan` 会生成立体声音频，因此 `ulaw_*`、`alaw_*` 和 `pcm_*` 输出格式会返回 400。音效不会改变请求费用。

## Response

### 200

流式音频数据

- Streaming response of `string`.

## Errors

### 422 Unprocessable Entity Error

验证错误。

- `detail` (list of ValidationError, optional)

## Types

### VoiceSettingsResponseModel

- `stability` (double, optional, nullable, default: 0.5) — 决定音色的稳定性以及每次生成之间的随机性。较低的值会带来更丰富的情感范围。较高的值可能使音色较为单调，情感有限。
- `use_speaker_boost` (boolean, optional, nullable, default: true) — 此设置可提高与原始说话者的相似度。使用后计算负载会略微增加，从而提高延迟。
- `similarity_boost` (double, optional, nullable, default: 0.75) — 决定 AI 在尝试复现原始音色时应遵循原始音色的程度。
- `style` (double, optional, nullable, default: 0) — 决定音色的风格夸张程度。此设置会尝试增强原始说话者的风格。设为非 0 值时会消耗额外计算资源，并可能增加延迟。
- `speed` (double, optional, nullable, default: 1) — 调整语速。值为 1.0 时使用默认语速；小于 1.0 会减慢语音，大于 1.0 会加快语音。
- `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
{
  "text": "The first move is what sets everything in motion.",
  "model_id": "eleven_multilingual_v2"
}
```

**SDK Code**

```python
import requests

url = "https://api.elevenlabs.io/v1/text-to-speech/JBFqnCBsd6RMkjVDRZzb/stream"

querystring = {"output_format":"mp3_44100_128"}

payload = {
    "text": "The first move is what sets everything in motion.",
    "model_id": "eleven_multilingual_v2"
}
headers = {
    "xi-api-key": "xi-api-key",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript
const url = 'https://api.elevenlabs.io/v1/text-to-speech/JBFqnCBsd6RMkjVDRZzb/stream?output_format=mp3_44100_128';
const options = {
  method: 'POST',
  headers: {'xi-api-key': 'xi-api-key', 'Content-Type': 'application/json'},
  body: '{"text":"The first move is what sets everything in motion.","model_id":"eleven_multilingual_v2"}'
};

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-speech/JBFqnCBsd6RMkjVDRZzb/stream?output_format=mp3_44100_128"

	payload := strings.NewReader("{\n  \"text\": \"The first move is what sets everything in motion.\",\n  \"model_id\": \"eleven_multilingual_v2\"\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-speech/JBFqnCBsd6RMkjVDRZzb/stream?output_format=mp3_44100_128")

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  \"text\": \"The first move is what sets everything in motion.\",\n  \"model_id\": \"eleven_multilingual_v2\"\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-speech/JBFqnCBsd6RMkjVDRZzb/stream?output_format=mp3_44100_128")
  .header("xi-api-key", "xi-api-key")
  .header("Content-Type", "application/json")
  .body("{\n  \"text\": \"The first move is what sets everything in motion.\",\n  \"model_id\": \"eleven_multilingual_v2\"\n}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.elevenlabs.io/v1/text-to-speech/JBFqnCBsd6RMkjVDRZzb/stream?output_format=mp3_44100_128', [
  'body' => '{
  "text": "The first move is what sets everything in motion.",
  "model_id": "eleven_multilingual_v2"
}',
  '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-speech/JBFqnCBsd6RMkjVDRZzb/stream?output_format=mp3_44100_128");
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  \"text\": \"The first move is what sets everything in motion.\",\n  \"model_id\": \"eleven_multilingual_v2\"\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 = [
  "text": "The first move is what sets everything in motion.",
  "model_id": "eleven_multilingual_v2"
] as [String : Any]

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

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