> 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}/with-timestamps
Content-Type: application/json

根据文本生成语音，并提供精确的字符级时间信息以实现音文同步。

Reference: https://elevenlabs.io/docs/api-reference/text-to-speech/convert-with-timestamps

## 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。可通过 https://api.elevenlabs.io/v1/voices 列出所有可用音色。

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

### Body (application/json)

This endpoint expects a Body_text_to_speech_full_with_timestamps.

- `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) — 要应用于文本的发音词典定位符（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) — 本次生成之前样本的 request_id 列表。将大型任务拆分为多个请求时，可用于提升语音连贯性。所有生成使用同一模型时效果最佳。如果同时发送 previous_text 和 previous_request_ids，将忽略 previous_text。最多可发送 3 个 request_ids。
- `next_request_ids` (list of string, optional) — 本次生成后续样本的 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

成功响应

- `audio_base64` (string, required) — Base64 encoded audio data
- `alignment` (CharacterAlignmentResponseModel, optional, nullable) — 原始文本中每个字符的时间戳信息。
- `normalized_alignment` (CharacterAlignmentResponseModel, optional, nullable) — 规范化文本中每个字符的时间戳信息。

## 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（最右）。仅音色会进行声像定位；混响和背景噪声保持居中。

### CharacterAlignmentResponseModel

- `characters` (list of string, required)
- `character_start_times_seconds` (list of double, required)
- `character_end_times_seconds` (list of double, required)

### ValidationError

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

### ValidationErrorLocItems

- string
- integer

## Examples

**Request**

```json
{
  "text": "This is a test for the API of ElevenLabs."
}
```

**Response**

```json
{
  "audio_base64": "base64_encoded_audio_string",
  "alignment": {
    "characters": [
      "H",
      "e",
      "l",
      "l",
      "o"
    ],
    "character_start_times_seconds": [
      0,
      0.1,
      0.2,
      0.3,
      0.4
    ],
    "character_end_times_seconds": [
      0.1,
      0.2,
      0.3,
      0.4,
      0.5
    ]
  },
  "normalized_alignment": {
    "characters": [
      "H",
      "e",
      "l",
      "l",
      "o"
    ],
    "character_start_times_seconds": [
      0,
      0.1,
      0.2,
      0.3,
      0.4
    ],
    "character_end_times_seconds": [
      0.1,
      0.2,
      0.3,
      0.4,
      0.5
    ]
  }
}
```

**SDK Code**

```python
import requests

url = "https://api.elevenlabs.io/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM/with-timestamps"

payload = { "text": "This is a test for the API of ElevenLabs." }
headers = {"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-speech/21m00Tcm4TlvDq8ikWAM/with-timestamps';
const options = {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: '{"text":"This is a test for the API of ElevenLabs."}'
};

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/21m00Tcm4TlvDq8ikWAM/with-timestamps"

	payload := strings.NewReader("{\n  \"text\": \"This is a test for the API of ElevenLabs.\"\n}")

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

	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/21m00Tcm4TlvDq8ikWAM/with-timestamps")

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

request = Net::HTTP::Post.new(url)
request["Content-Type"] = 'application/json'
request.body = "{\n  \"text\": \"This is a test for the API of ElevenLabs.\"\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/21m00Tcm4TlvDq8ikWAM/with-timestamps")
  .header("Content-Type", "application/json")
  .body("{\n  \"text\": \"This is a test for the API of ElevenLabs.\"\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/21m00Tcm4TlvDq8ikWAM/with-timestamps', [
  'body' => '{
  "text": "This is a test for the API of ElevenLabs."
}',
  'headers' => [
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp
using RestSharp;

var client = new RestClient("https://api.elevenlabs.io/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM/with-timestamps");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"text\": \"This is a test for the API of ElevenLabs.\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = ["Content-Type": "application/json"]
let parameters = ["text": "This is a test for the API of ElevenLabs."] as [String : Any]

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

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