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

# 转写文本与提交策略

> **Note**
>
> **操作指南** · 假设你已完成
> [客户端](/docs/zh/eleven-api/guides/how-to/speech-to-text/realtime/client-side-streaming)或
> [服务端流式传输](/docs/zh/eleven-api/guides/how-to/speech-to-text/realtime/server-side-streaming)指南。

## 概述

转写音频时，你会收到部分转写文本和已提交的转写文本。

* **部分转写文本**：转写过程中的临时结果
* **已提交的转写文本**：收到“commit”消息时发送的最终转写片段结果。一个会话可以包含多个已提交的转写文本。

提交的转写文本可选择包含词级时间戳。仅当“include timestamps”选项设为 `true` 时才会收到这些时间戳。

```python
# Initialize the connection
connection = await elevenlabs.speech_to_text.realtime.connect(RealtimeUrlOptions(
  model_id="scribe_v2_realtime",
  include_timestamps=True, # Include this to receive the RealtimeEvents.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS event with word-level timestamps
))
```

```typescript
// Initialize the connection
const connection = await elevenlabs.speechToText.realtime.connect({
  modelId: "scribe_v2_realtime",
  includeTimestamps: true, // Include this to receive the RealtimeEvents.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS event with word-level timestamps
});
```

**`React`**

```typescript title="React"
const connection = useScribe({
  modelId: "scribe_v2_realtime",
  // Configuring this callback will automatically set the `includeTimestamps` option to `true`
  onCommittedTranscriptWithTimestamps: (data) => {
    console.log("Committed with timestamps:", data.text);
    console.log("Timestamps:", data.words);
  },
});
```

**`JavaScript`**

```typescript title="JavaScript"
const connection = Scribe.connect({
  modelId: "scribe_v2_realtime",
  includeTimestamps: true, // Include this to receive the RealtimeEvents.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS event with word-level timestamps
});
```

## 提交策略

通过 WebSocket 发送音频块时，可通过两种方式提交转写片段：手动提交或语音活动检测（VAD）。

### 手动提交

使用手动提交策略时，可自行控制何时提交转写片段。这是默认使用的策略。提交片段会清除已处理的累计转写文本，并在不丢失上下文的情况下开始新片段。建议每 20-30 秒提交一次，以改善延迟。即使不手动提交，模型也会在累计约 36 秒音频后自动提交。

为获得最佳效果，请在静音期间或轮次结束等其他合理时机提交。

> **Info**
>
> 发送前 2 秒音频后，才会开始处理转写。

```python
await connection.send({
  "audio_base_64": audio_base_64,
  "sample_rate": 16000,
})

# When ready to finalize the segment
await connection.commit()
```

```typescript
connection.send({
  audioBase64: audioBase64,
  sampleRate: 16000,
});

// When ready to finalize the segment
connection.commit();
```

> **Warning**
>
> 在短时间内连续多次手动提交可能会降低模型性能。

#### 发送先前文本上下文

发送音频进行转写时，可在第一个音频块中一并发送先前文本上下文，帮助模型理解语音上下文。这在以下场景中很有用：

* 对话式 AI 用例中的智能体文本：让模型更容易理解对话上下文，生成更好的转写结果。
* 网络错误后重新连接：让模型以先前文本为参考继续转写。
* 通用上下文信息：简短说明转写内容，有助于模型理解上下文。

> **Warning**
>
> 仅在通过 `connection.send()` 发送第一个音频块时才能发送 `previous_text` 上下文。
> 在后续音频块中发送会导致错误。先前文本最好控制在 *50* 个字符以内。

```python
await connection.send({
  "audio_base_64": audio_base_64,
  "previous_text": "The previous text context",
})
```

```typescript
connection.send({
  audioBase64: audioBase64,
  previousText: "The previous text context",
});
```

### 语音活动检测（VAD）

使用 VAD 策略时，转写引擎会自动检测语音和静音片段。达到静音阈值后，转写引擎会自动提交转写片段。

在[客户端集成](/docs/zh/eleven-api/guides/how-to/speech-to-text/realtime/client-side-streaming)中转写麦克风音频时，建议使用 VAD 策略。

`vad_silence_threshold_secs` 接受 0.192 至 3.0 秒。JavaScript 和 React SDK 仅接受 0.3 至 3.0。

**`客户端`**

```typescript title="客户端"
import { Scribe, AudioFormat, CommitStrategy } from "@elevenlabs/client";

const connection = Scribe.connect({
  token: "sutkn_1234567890",
  modelId: "scribe_v2_realtime",
  audioFormat: AudioFormat.PCM_16000,
  commitStrategy: CommitStrategy.VAD,
  vadSilenceThresholdSecs: 1.5,
  vadThreshold: 0.4,
  minSpeechDurationMs: 100,
  minSilenceDurationMs: 100,
});
```

```python
from dotenv import load_dotenv
from elevenlabs import AudioFormat, CommitStrategy, ElevenLabs, RealtimeAudioOptions

load_dotenv()

elevenlabs = ElevenLabs(api_key=os.getenv("ELEVENLABS_API_KEY"))

connection = await elevenlabs.speech_to_text.realtime.connect(
    RealtimeAudioOptions(
        model_id="scribe_v2_realtime",
        audio_format=AudioFormat.PCM_16000,
        commit_strategy=CommitStrategy.VAD,
        vad_silence_threshold_secs=1.5,
        vad_threshold=0.4,
        min_speech_duration_ms=100,
        min_silence_duration_ms=100,
    )
)
```

**`TypeScript`**

```typescript title="TypeScript"
import { ElevenLabsClient, AudioFormat, CommitStrategy } from '@elevenlabs/elevenlabs-js';

const elevenlabs = new ElevenLabsClient();

const connection = await elevenlabs.speechToText.realtime.connect({
  modelId: "scribe_v2_realtime",
  audioFormat: AudioFormat.PCM_16000,
  commitStrategy: CommitStrategy.VAD,
  vadSilenceThresholdSecs: 1.5,
  vadThreshold: 0.4,
  minSpeechDurationMs: 100,
  minSilenceDurationMs: 100,
});
```

## 过滤背景音频

设置 `filter_background_audio=true` 查询参数，可减少背景语音（如附近交谈）和环境噪音导致的误触发。启用过滤后，语音活动检测会使用针对忽略背景语音优化的模型；除非自行设置，否则 `vad_threshold` 默认为 `0.15`。

> **Warning**
>
> `filter_background_audio` 不能与 `include_timestamps` 同时使用。如果同时设置，服务器会
> 发送 `invalid_request` 错误并关闭连接。

过滤不会改变计费方式：包括过滤器忽略的音频在内，所有流式传输的音频都会计费。

## 在静音期间保持连接

官方 SDK 不会在没有消息到达时断开连接，因此大多数集成无需此设置。如果自建的 WebSocket 客户端，或中间的代理或负载均衡器，会在一段时间未收到帧时关闭连接，请在连接时传入可选的 `keepalive_interval_ms` 查询参数。这在长时间静音时很重要，例如通话中有 10-15 秒停顿。服务器会大约每个间隔发送一次保活 `partial_transcript`：如果当前片段没有未提交文本，则为空（`text: ""`）；否则重复最新的部分文本。

> **Warning**
>
> 保活不是自由运行的 ping：必须持续流式传输音频（静音帧也可以）。
> 如果停止发送音频，则不会发送保活消息，且服务器会在 15 秒内未收到任何客户端消息后关闭连接。
> 此服务器限制不可配置。

* 接受介于 `500` 和 `10000` 之间的整数（毫秒）。默认禁用；省略该参数即可保持现有行为。
* 超出范围或非整数值会导致服务器发送 `invalid_request` 错误并关闭连接。
* 保活由模型实际处理发送的静音音频驱动，而非自由运行的计时器，因此也能确认转写链路处于正常状态。
* 音频大约按 1 秒的块处理，因此保活消息会按此节奏取整后大约每个间隔到达一次（例如，`1000` 大约每秒触发一次，`3000` 大约每 3 秒触发一次）。由于服务器会在转写前缓冲前约 2 秒音频，会话的首次保活会在开始约 2 秒后到达。请将间隔设为最多约为自身读取超时的三分之一，以预留余量。
* 仅当当前片段尚无未提交文本时，保活的 `text` 才为空。如果语音后、提交前发生停顿（在 `filter_background_audio=true` 或未提交的手动提交模式下最明显），保活会改为重复最新部分文本，因此不会清空临时文本。提交后，在新语音到达前，保活会恢复为空。
* 支持 `commit_strategy=manual` 和 `commit_strategy=vad`，也支持 `filter_background_audio=true`。除已流式传输的音频外，不会产生额外计费影响。
* `session_started` 消息的 `config` 会回显 `keepalive_interval_ms`（禁用时为 `null`）。

> **Info**
>
> 空的 `partial_transcript`（`text: ""`）表示“当前片段中没有语音”。停顿期间重复且
> 相同的 `partial_transcript` 也是保活消息——客户端应照常渲染部分转写文本，无需对重复内容作特殊处理。

将参数添加到 WebSocket URL：

```text
wss://api.elevenlabs.io/v1/speech-to-text/realtime?model_id=scribe_v2_realtime&commit_strategy=vad&keepalive_interval_ms=1000
```

## 支持的音频格式

| 格式        | 采样率       | 描述               |
| --------- | --------- | ---------------- |
| pcm_8000  | 8 kHz     | 16 位 PCM，小端序     |
| pcm_16000 | 16 kHz    | 16 位 PCM，小端序（推荐） |
| pcm_22050 | 22.05 kHz | 16 位 PCM，小端序     |
| pcm_24000 | 24 kHz    | 16 位 PCM，小端序     |
| pcm_44100 | 44.1 kHz  | 16 位 PCM，小端序     |
| pcm_48000 | 48 kHz    | 16 位 PCM，小端序     |
| ulaw_8000 | 8 kHz     | 8 位 μ-law 编码     |

## 最佳实践

### 音频质量

* 为兼顾质量和带宽，建议使用 16 kHz 采样率。
* 确保音频输入清晰，尽量减少背景噪音。
* 使用合适的麦克风增益，避免削波。
* 目前仅支持单声道音频。

### 音频块大小

* 为实现流畅传输，请发送时长为 0.1-1 秒的音频块。
* 更小的音频块延迟更低，但开销更大。
* 更大的音频块效率更高，但可能会增加延迟。

## 后续步骤

#### [服务端流式传输](/docs/zh/eleven-api/guides/how-to/speech-to-text/realtime/server-side-streaming)

使用 WebSocket API 设置服务端音频转写。

#### [事件参考](/docs/zh/eleven-api/guides/how-to/speech-to-text/realtime/event-reference)

查看实时 STT API 的完整事件和错误类型列表。