> For the complete documentation index, see [llms.txt](https://docs.convai.com/api-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/transcript-api.md).

# 转录 API

使用转录文本门面，在 Unity 脚本中查询转录文本回合、订阅实时变更、读取字幕并导出会话历史记录。

`ConvaiTranscripts` 是 Convai Unity SDK 的规范转录文本门面：一个实时的内存时间线，记录房间内玩家和角色的每一轮对话，并提供拉取式查询、推送式变更事件、实时字幕以及会话导出辅助功能。在编写自定义聊天 UI、导出转录文本或处理轮次级对话逻辑时，请参阅此页面。通过以下方式访问该门面： `ConvaiManager.ActiveManager.Transcripts`.

***

### 推送与拉取

|          | `ConvaiCharacter.OnTranscriptReceived`                        | 事件中继（`ConvaiTranscriptEventRelay`, `ConvaiEvents`)                 | `ConvaiTranscripts`                                          |
| -------- | ------------------------------------------------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------ |
| **传递方式** | 推送 — 每次更新都会触发普通 C# 事件，内容仅限于单个角色自己的发言                          | 推送 — Inspector `UnityEvent`或 C# 事件会在每次更新时触发                        | 拉取（`CurrentTimeline`, `GetTurns`）和推送（`Changed`, `Subscribe`) |
| **历史记录** | 仅包含当前更新，范围限定为该角色                                              | 仅包含当前更新                                                            | 完整历史记录：进行中的轮次、已提交的轮次以及实时字幕                                   |
| **使用场景** | 角色范围内的推送响应 — 注视、手势、单角色字幕                                      | 字幕渲染、按角色触发动画                                                       | 自定义聊天 UI、会话结束后导出、轮次级评估逻辑                                     |
| **访问方式** | `character.OnTranscriptReceived` （位于一个 `ConvaiCharacter` 引用上） | `ConvaiTranscriptEventRelay`, `ConvaiManager.ActiveManager.Events` | `ConvaiManager.ActiveManager.Transcripts`                    |

***

### `ConvaiCharacter.OnTranscriptReceived`

`OnTranscriptReceived` 是声明在 `ConvaiCharacter`: `event Action<string, bool> OnTranscriptReceived`上的普通 C# 事件。它是下文所述 `ConvaiTranscripts` 门面的角色级对应接口——如果你已经持有某个 `ConvaiCharacter` 的引用，并且希望直接接收该角色自身发言的推送通知，而不订阅房间级门面或添加事件中继组件，就可以使用它。

```csharp
character.OnTranscriptReceived += HandleTranscript;

private void HandleTranscript(string text, bool isFinal)
{
    if (!isFinal) return; // 丢弃中间结果，避免重复追加句子
    _log.text += $"\n{text}";
}
```

第一个参数是转录文本。第二个参数 `isFinal`取自消息本身的生命周期状态——一条已确定的发言会报告 `true`；仍在流式传输的行会报告 `false`.

文本按句子而非合成块到达。句子在定稿前以流式方式传输时，会被发送 **两次**：一次为 `isFinal` `false` 表示句子仍在生成过程中，另一次为 `isFinal` `true` 表示句子已定稿。如果处理程序每次调用都追加文本而不检查 `isFinal` ，就会导致句子重复。

`OnTranscriptReceived` 仅针对该角色自身说出的内容触发——未说出口的机器人文本会被过滤掉；传入消息会先通过参与者 ID 与该角色匹配，若无法匹配，则回退到角色 ID。

对于单个角色的推送式响应，请使用 `ConvaiCharacter.OnTranscriptReceived` 。如果需要完整的房间历史记录、多个角色或玩家的数据，或需要通过拉取方式查询，请使用下文的 `ConvaiTranscripts` 。

***

### `ConvaiTranscripts` 门面

```csharp
ConvaiManager manager = ConvaiManager.ActiveManager;
if (manager == null || !manager.TryGetTranscripts(out ConvaiTranscripts transcripts))
    return;
```

`ConvaiManager.ActiveManager.Transcripts` 会在 SDK 尚未完成引导初始化时抛出 `InvalidOperationException` 。如果调用方可能在初始化完成前运行（例如在 `manager.TryGetTranscripts(out ConvaiTranscripts transcripts)` 中），请使用 `OnEnable`.

#### 属性

| 成员                      | 类型                          | 说明                                 |
| ----------------------- | --------------------------- | ---------------------------------- |
| `CurrentTimeline`       | `TranscriptTimeline`        | 当前转录时间线。底层引擎快照发生变化之前，始终返回同一实例。     |
| `CurrentCaptions`       | `TranscriptCaptionSnapshot` | 当前实时字幕快照，用于与语音同步的字幕。               |
| `IsPresentationEnabled` | `bool`                      | 是否应由随附的演示组件呈现转录更新。只读；规范历史记录仍会持续记录。 |

#### 事件

| 事件                           | 参数                          | 触发时机                                |
| ---------------------------- | --------------------------- | ----------------------------------- |
| `Changed`                    | `TranscriptChangeBatch`     | 添加、更新、提交、中断、更正或移除了一个或多个轮次           |
| `TurnUpdated`                | `TranscriptTurn`            | 轮次收到新文本或发生非终止状态变更                   |
| `TurnCommitted`              | `TranscriptTurn`            | 轮次状态转换为 `Committed` 或 `Interrupted` |
| `TurnCorrected`              | `TranscriptTurn`            | 先前已提交轮次的文本被更正                       |
| `TurnRemoved`                | `string` （回合 ID）            | 从时间线中移除一个回合                         |
| `CaptionsChanged`            | `TranscriptCaptionSnapshot` | 实时字幕快照发生变化                          |
| `PresentationEnabledChanged` | `bool`                      | `IsPresentationEnabled` 发生变化        |

#### 方法

| 方法                                                                                                           | 返回                              | 说明                                                                                             |
| ------------------------------------------------------------------------------------------------------------ | ------------------------------- | ---------------------------------------------------------------------------------------------- |
| `GetTurns(TranscriptQuery query = null)`                                                                     | `IReadOnlyList<TranscriptTurn>` | 返回与可选查询条件匹配的所有回合。传入 `null` 以获取所有回合。                                                            |
| `GetTurn(string turnId)`                                                                                     | `TranscriptTurn`                | 按 ID 获取指定回合。若未找到，则返回 `null` 。                                                                  |
| `GetLatestTurn(TranscriptParticipantRef participant)`                                                        | `TranscriptTurn`                | 返回指定参与者最近的回合。若没有，则返回 `null` 。                                                                  |
| `Subscribe(Action<TranscriptChange> callback, TranscriptSubscriptionOptions options = null)`                 | `IDisposable`                   | 注册一个回调，以接收匹配的回合变更。释放返回值即可取消订阅。                                                                 |
| `SubscribeCommitted(Action<TranscriptChange> callback, TranscriptSubscriptionOptions options = null)`        | `IDisposable`                   | 快捷方式，相当于调用 `Subscribe` 并设置 `IncludeActive = false` 和 `IncludeTerminal = true` ——仅包含已提交和已中断的回合。 |
| `SubscribeCaptions(Action<TranscriptCaption> callback, TranscriptCaptionSubscriptionOptions options = null)` | `IDisposable`                   | 注册一个回调，以接收实时字幕更新。                                                                              |
| `Clear()`                                                                                                    | `void`                          | 清除规范转录历史记录。                                                                                    |
| `Export(TranscriptExportFormat format)`                                                                      | `string`                        | 将所有已提交的回合序列化为纯文本、Markdown 或 JSON。                                                              |
| `Dispose()`                                                                                                  | `void`                          | 取消订阅内部引擎事件。所属组件销毁时调用。                                                                          |

```csharp
transcripts.Changed += OnTranscriptChanged;

private void OnTranscriptChanged(TranscriptChangeBatch batch)
{
    foreach (TranscriptChange change in batch.Changes)
    {
        if (change.Kind == TranscriptChangeKind.Removed || change.Turn == null) continue;
        Debug.Log($"[{change.Turn.Speaker.DisplayName}] {change.Turn.DisplayText}");
    }
}
```

***

### `TranscriptTimeline`

| 属性            | 类型                                            | 说明                                   |
| ------------- | --------------------------------------------- | ------------------------------------ |
| `Cursor`      | `long`                                        | 时间线每次更新时都会改变的单调递增值                   |
| `ActiveTurns` | `IReadOnlyList<TranscriptTurn>`               | 尚未提交的回合（`正在监听`, `正在流式传输`，或 `稳定`)     |
| `已提交轮次`       | `IReadOnlyList<TranscriptTurn>`               | 处于终止状态的轮次（`已提交` 或 `已中断`)             |
| `按 ID 索引的轮次`  | `IReadOnlyDictionary<string, TranscriptTurn>` | 所有轮次，按 `TranscriptTurn.Id`           |
| `轮次`          | `IReadOnlyList<TranscriptTurn>`               | `活动轮次` 和 `已提交轮次` 合并后按 `RoomSequence` |

`TranscriptTimeline.Empty` 是一个静态、可重复使用的空实例，可在会话连接前作为安全的默认值。

***

### `TranscriptTurn`

| 属性               | 类型                                 | 说明                                             |
| ---------------- | ---------------------------------- | ---------------------------------------------- |
| `ID`             | `string`                           | 此轮次的唯一标识符                                      |
| `MessageId`      | `string`                           | 与此轮次关联的消息标识符                                   |
| `ResponseId`     | `string`                           | （如适用）与此轮次关联的响应标识符                              |
| `RoomSequence`   | `long`                             | 房间内单调递增的序列号                                    |
| `修订版本`           | `int`                              | 每当轮次内容或状态发生变化时递增                               |
| `发言者`            | `TranscriptSpeaker`                | 产生此轮次的对象                                       |
| `State`          | `TranscriptTurnState`              | 此轮次当前的生命周期状态                                   |
| `主要文本来源`         | `TranscriptTextSource`             | 此轮次显示文本的主要来源                                   |
| `稳定文本`           | `string`                           | 已定稿的文本，后续更新不会再改变                               |
| `中间文本`           | `string`                           | 当前流式传输片段中尚在生成的文本                               |
| `显示文本`           | `string`                           | 要为此轮次渲染的文本——由以下内容组合而成： `稳定文本` 和 `中间文本`         |
| `开始时间（UTC）`      | `DateTime`                         | 此轮次开始的 UTC 时间                                  |
| `最后更新时间（UTC）`    | `DateTime`                         | 最近一次更新的 UTC 时间                                 |
| `CommittedAtUtc` | `DateTime?`                        | 提交此轮的 UTC 时间； `null` 表示仍处于活动状态                 |
| `WasInterrupted` | `bool`                             | `true` 表示此轮因中断而结束                              |
| `Segments`       | `IReadOnlyList<TranscriptSegment>` | 组成此轮的各个转录片段                                    |
| `HasText`        | `bool`                             | `true` 当 `DisplayText` 非空时                     |
| `IsCommitted`    | `bool`                             | `true` 当 `State` 为 `Committed` 或 `Interrupted` |

{% hint style="info" %}
使用 `DisplayText` 进行实时渲染。它会合并 `StableText` 和 `InterimText`，因此无论 `State`.
{% endhint %}

#### `TranscriptTurnState` 枚举值如何，始终显示当前可用的最完整文本

| 值                 | 说明                                                 |
| ----------------- | -------------------------------------------------- |
| `Listening` (0)   | 此轮已开启，正在等待语音或文本输入；尚未捕获任何文本                         |
| `Streaming` (1)   | 此轮正在接收文本； `InterimText` 会持续更新                      |
| `Stable` (2)      | 流式传输已暂停；文本已稳定，但此轮尚未提交                              |
| `Committed` (4)   | 此轮已完全提交； `StableText` 为最终文本                        |
| `Interrupted` (5) | 此轮因中断而结束（`WasInterrupted` 为 `true`)                |
| `Discarded` (6)   | 回合已关闭，且没有文本，因此未纳入 `ActiveTurns` 和 `CommittedTurns` |

***

### `TranscriptSegment`

| 属性             | 类型                     | 说明                                      |
| -------------- | ---------------------- | --------------------------------------- |
| `ID`           | `string`               | 此片段的唯一标识符                               |
| `TurnId`       | `string`               | 父级 TranscriptTurn 的 ID `TranscriptTurn` |
| `发言者`          | `TranscriptSpeaker`    | 此片段的生成者                                 |
| `稳定文本`         | `string`               | 此片段的最终文本                                |
| `中间文本`         | `string`               | 此片段进行中的文本                               |
| `显示文本`         | `string`               | 要为此片段呈现的文本                              |
| `State`        | `TranscriptTurnState`  | 此片段的生命周期状态                              |
| `Source`       | `TranscriptTextSource` | 此片段文本的来源                                |
| `开始时间（UTC）`    | `DateTime`             | 此片段开始的 UTC 时间                           |
| `UpdatedAtUtc` | `DateTime`             | 最近一次更新的 UTC 时间                          |
| `StoppedAtUtc` | `DateTime?`            | 此片段停止的 UTC 时间； `null` 处于活动状态时           |

#### `TranscriptTextSource` 枚举

| 值                         | 说明                   |
| ------------------------- | -------------------- |
| `Unknown` (0)             | 无法确定来源               |
| `InterimAsr` (1)          | 进行中的语音转文本识别          |
| `AsrFinal` (2)            | 最终语音转文本识别结果          |
| `ProcessedFinal` (3)      | 经玩家端处理后的最终文本         |
| `TypedText` (4)           | 玩家输入的文本，而非说出的内容      |
| `BotOutput` (5)           | 角色的最终回复文本            |
| `BotPreview` (6)          | 角色进行中的回复预览（LLM 流式输出） |
| `LegacyBotTranscript` (7) | 来自旧版管线的角色转录文本        |

***

### `TranscriptSpeaker`

| 属性              | 类型                      | 说明                                     |
| --------------- | ----------------------- | -------------------------------------- |
| `Type`          | `TranscriptSpeakerType` | 此说话者是 `Player`, `Character`还是 `System` |
| `ID`            | `string`                | 此说话者的角色 ID 或玩家 ID                      |
| `DisplayName`   | `string`                | 人类可读的名称                                |
| `ParticipantId` | `string`                | 房间级参与者标识符                              |

#### `TranscriptSpeakerType` 枚举

| 值               | 说明                  |
| --------------- | ------------------- |
| `Player` (0)    | 人类玩家参与者             |
| `Character` (1) | AI 角色参与者            |
| `System` (2)    | 由系统发起的发言者，不与玩家或角色关联 |

***

### `TranscriptChange` 和 `TranscriptChangeBatch`

`TranscriptChange`:

| 属性       | 类型                     | 说明                                  |
| -------- | ---------------------- | ----------------------------------- |
| `Kind`   | `TranscriptChangeKind` | 此实例所表示的更改类型                         |
| `Turn`   | `TranscriptTurn`       | 受影响的轮次； `null` 当 `Kind` 为 `Removed` |
| `TurnId` | `string`               | 受影响轮次的 ID                           |

`TranscriptChangeBatch`:

| 属性             | 类型                                | 说明                                   |
| -------------- | --------------------------------- | ------------------------------------ |
| `Timeline`     | `TranscriptTimeline`              | 应用此批更改后的完整时间线                        |
| `Changes`      | `IReadOnlyList<TranscriptChange>` | 此批次包含的所有更改                           |
| `ChangedTurns` | `IReadOnlyList<TranscriptTurn>`   | 便捷访问器：所有非 null 的 `Turn` 来自 `Changes` |

#### `TranscriptChangeKind` 枚举

| 值                 | 说明                     |
| ----------------- | ---------------------- |
| `Added` (0)       | 创建了一个新轮次               |
| `Updated` (1)     | 现有轮次收到了新文本，或发生了非终止状态更改 |
| `Committed` (2)   | 轮次转换为 `Committed`      |
| `Interrupted` (3) | 轮次转换为 `Interrupted`    |
| `Corrected` (4)   | 先前已提交轮次的文本已更正          |
| `Removed` (5)     | 轮次已从时间线中移除             |

***

### `TranscriptQuery` — 筛选器 `GetTurns` 结果

| 字段                      | 类型                           | 默认值         | 说明                              |
| ----------------------- | ---------------------------- | ----------- | ------------------------------- |
| `ParticipantKind`       | `TranscriptParticipantKind?` | `null` （全部） | 筛选 `Player` 或 `Character` 类型的回合 |
| `PlayerOrCharacterId`   | `string`                     | `null` （全部） | 筛选特定玩家或角色 ID                    |
| `ParticipantId`         | `string`                     | `null` （全部） | 筛选特定房间参与者 ID                    |
| `IncludeActiveTurns`    | `bool`                       | `true`      | 包含仍处于活动状态（尚未提交）的回合              |
| `IncludeCommittedTurns` | `bool`                       | `true`      | 包含已提交或已中断的回合                    |

```csharp
var query = new TranscriptQuery
{
    ParticipantKind      = TranscriptParticipantKind.Character,
    PlayerOrCharacterId  = "char_instructor_01",
    IncludeActiveTurns   = false,
    IncludeCommittedTurns = true
};

IReadOnlyList<TranscriptTurn> turns = transcripts.GetTurns(query);
```

`TranscriptQuery` 使用 `IncludeActiveTurns`/`和` 字段名。 `TranscriptSubscriptionOptions`由 `Subscribe`使用，采用 `IncludeActive`/`和` ，而非上述字段。

#### `TranscriptParticipantKind` 枚举

| 值               | 说明       |
| --------------- | -------- |
| `Player` (0)    | 人类玩家参与者  |
| `Character` (1) | AI 角色参与者 |

#### `TranscriptParticipantRef` 结构体

用作 `participant` 参数，传递给 `GetLatestTurn`.

| 属性                    | 类型                          | 说明                                             |
| --------------------- | --------------------------- | ---------------------------------------------- |
| `Kind`                | `TranscriptParticipantKind` | 此参与者是 `Player` 还是 `Character`                  |
| `PlayerOrCharacterId` | `string`                    | 此参与者的角色 ID 或玩家 ID                              |
| `DisplayName`         | `string`                    | 人类可读的名称                                        |
| `ParticipantId`       | `string`                    | 房间级参与者标识符                                      |
| `IsEmpty`             | `bool`                      | `true` 当 `PlayerOrCharacterId` 为 null 或仅包含空白字符 |

通过以下方式构造： `new TranscriptParticipantRef(TranscriptParticipantKind kind, string playerOrCharacterId, string displayName, string participantId = null)`。实现了 `IEquatable<TranscriptParticipantRef>` 以及 `==`/`!=` 运算符。

***

### `TranscriptSubscriptionOptions` —用于筛选 `Subscribe` 回调

| 字段                | 类型                       | 默认值         | 说明                                                                           |
| ----------------- | ------------------------ | ----------- | ---------------------------------------------------------------------------- |
| `ReplayExisting`  | `bool`                   | `false`     | 当 `true`, `Subscribe` 会立即为 CurrentTimeline 中已存在的每个匹配轮次调用回调 `CurrentTimeline` |
| `IncludeActive`   | `bool`                   | `true`      | 包含尚未提交的轮次                                                                    |
| `IncludeTerminal` | `bool`                   | `true`      | 包含已提交或已中断的轮次                                                                 |
| `SpeakerType`     | `TranscriptSpeakerType?` | `null` （全部） | 筛选特定的发言者类型                                                                   |
| `SpeakerId`       | `string`                 | `null` （全部） | 筛选特定的发言者 ID                                                                  |
| `ParticipantId`   | `string`                 | `null` （全部） | 筛选特定房间参与者 ID                                                                 |

***

### 实时字幕

字幕是与语音时间对齐的文本的一种独立临时投影，与持久化聊天记录分开保存，因此临时的 TTS 预览文本不会被视为规范对话历史记录。

#### `TranscriptCaption`

| 属性               | 类型                       | 说明                                             |
| ---------------- | ------------------------ | ---------------------------------------------- |
| `TurnId`         | `string`                 | 此字幕所对齐的转录轮次的 ID                                |
| `发言者`            | `TranscriptSpeaker`      | 生成此字幕的对象                                       |
| `Text`           | `string`                 | 字幕文本                                           |
| `State`          | `TranscriptCaptionState` | 当前字幕状态                                         |
| `UpdatedAtUtc`   | `DateTime`               | 最近一次更新的 UTC 时间                                 |
| `HasText`        | `bool`                   | `true` 当 `Text` 非空时                            |
| `IsFinal`        | `bool`                   | `true` 当 `State` 为 `Completed` 或 `Interrupted` |
| `WasInterrupted` | `bool`                   | `true` 当 `State` 为 `Interrupted`               |

#### `TranscriptCaptionState` 枚举

| 值                 | 说明                |
| ----------------- | ----------------- |
| `Streaming` (0)   | 字幕文本正在实时更新        |
| `Stable` (1)      | 字幕文本已暂停更新，但尚未最终定稿 |
| `Completed` (2)   | 字幕已正常结束           |
| `Interrupted` (3) | 字幕因回合中断而结束        |

#### `TranscriptCaptionSnapshot`

| 属性         | 类型                                 | 说明                 |
| ---------- | ---------------------------------- | ------------------ |
| `Cursor`   | `long`                             | 单调递增的值，每当字幕更新时都会变化 |
| `Captions` | `IReadOnlyList<TranscriptCaption>` | 当前实时字幕集合           |

`TranscriptCaptionSnapshot.Empty` 是一个静态且可重复使用的空实例。

#### `TranscriptCaptionSubscriptionOptions`

| 字段                 | 类型                       | 默认值         | 说明                                              |
| ------------------ | ------------------------ | ----------- | ----------------------------------------------- |
| `ReplayLatest`     | `bool`                   | `true`      | 当 `true`, `SubscribeCaptions` 会立即为每条当前匹配的字幕调用回调 |
| `IncludeStreaming` | `bool`                   | `true`      | 包括仍在更新的字幕                                       |
| `IncludeFinal`     | `bool`                   | `true`      | 包括已完成或因中断而结束的字幕                                 |
| `SpeakerType`      | `TranscriptSpeakerType?` | `null` （全部） | 筛选特定的发言者类型                                      |
| `SpeakerId`        | `string`                 | `null` （全部） | 筛选特定的发言者 ID                                     |
| `ParticipantId`    | `string`                 | `null` （全部） | 筛选特定房间参与者 ID                                    |

***

### 导出转录文本

`Export(TranscriptExportFormat format)` 会将 `CurrentTimeline.CommittedTurns`中的每个回合按 `RoomSequence`排序后序列化为单个字符串。说话者标签为空时，会回退使用 `Speaker.Type` （当 `Speaker.DisplayName` 为空时）。

#### `TranscriptExportFormat` 枚举

| 值               | 说明                                         |
| --------------- | ------------------------------------------ |
| `PlainText` (0) | 每个回合占一行： `speaker: text`                   |
| `Markdown` (1)  | 每个回合占一行： `**speaker:** text`，回合之间空一行       |
| `Json` (2)      | 缩进格式的 JSON 数组，其中包含已提交的 `TranscriptTurn` 对象 |

***

### 使用示例

#### 示例 1 — 会话结束后导出转录文本

医疗培训模拟系统会在会话结束后将完整的会话转录文本导出为 JSON，供督导人员审核。

{% code title="TranscriptExporter.cs" %}

```csharp
using Convai.Domain.Models;
using Convai.Runtime.Components;
using Convai.Runtime.Facades;
using System.IO;
using UnityEngine;

public class TranscriptExporter : MonoBehaviour
{
    public void ExportToJson(string outputPath)
    {
        ConvaiManager manager = ConvaiManager.ActiveManager;
        if (manager == null || !manager.TryGetTranscripts(out ConvaiTranscripts transcripts))
            return;

        string json = transcripts.Export(TranscriptExportFormat.Json);
        File.WriteAllText(outputPath, json);
        Debug.Log($"Transcript saved to {outputPath}");
    }
}
```

{% endcode %}

#### 示例 2 — 提交时追加的响应式聊天记录

企业入职模拟会构建可滚动的聊天记录，并且只在对话轮次提交时追加消息，从而避免中间更新造成闪烁。

{% code title="CompletedTurnChatLog.cs" %}

```csharp
using Convai.Domain.Models;
using Convai.Runtime.Components;
using Convai.Runtime.Facades;
using System;
using TMPro;
using UnityEngine;

public class CompletedTurnChatLog : MonoBehaviour
{
    [SerializeField] private TMP_Text _log;

    private IDisposable _subscription;

    private void OnEnable()
    {
        ConvaiManager manager = ConvaiManager.ActiveManager;
        if (manager == null || !manager.TryGetTranscripts(out ConvaiTranscripts transcripts))
            return;

        _subscription = transcripts.SubscribeCommitted(OnTurnCommitted, new TranscriptSubscriptionOptions
        {
            ReplayExisting = true
        });
    }

    private void OnDisable() => _subscription?.Dispose();

    private void OnTurnCommitted(TranscriptChange change)
    {
        if (change.Turn == null) return;
        _log.text += $"\n<b>{change.Turn.Speaker.DisplayName}:</b> {change.Turn.DisplayText}";
    }
}
```

{% endcode %}

#### 示例 3 — 带实时字幕的聊天记录

工业安全演练会在启用时重放已提交的聊天记录，随后让字幕行与实时字幕保持同步——与持久化的聊天记录分开处理。

{% code title="LiveChatAndSubtitleUI.cs" %}

```csharp
using Convai.Domain.Models;
using Convai.Runtime.Components;
using Convai.Runtime.Facades;
using System;
using System.Linq;
using TMPro;
using UnityEngine;

public class LiveChatAndSubtitleUI : MonoBehaviour
{
    [SerializeField] private TMP_Text _chatContent;
    [SerializeField] private TMP_Text _subtitleText;

    private IDisposable _chatSubscription;
    private IDisposable _captionSubscription;

    private void OnEnable()
    {
        ConvaiManager manager = ConvaiManager.ActiveManager;
        if (manager == null || !manager.TryGetTranscripts(out ConvaiTranscripts transcripts))
            return;

        _chatContent.text = string.Join("\n",
            transcripts.CurrentTimeline.CommittedTurns
                .OrderBy(turn => turn.RoomSequence)
                .Select(turn => $"<b>{turn.Speaker.DisplayName}:</b> {turn.DisplayText}"));

        _chatSubscription = transcripts.SubscribeCommitted(OnTurnCommitted);
        _captionSubscription = transcripts.SubscribeCaptions(OnCaption);
    }

    private void OnDisable()
    {
        _chatSubscription?.Dispose();
        _captionSubscription?.Dispose();
    }

    private void OnTurnCommitted(TranscriptChange change)
    {
        if (change.Turn == null) return;
        _chatContent.text += $"\n<b>{change.Turn.Speaker.DisplayName}:</b> {change.Turn.DisplayText}";
    }

    private void OnCaption(TranscriptCaption caption) => _subtitleText.text = caption.Text;
}
```

{% endcode %}

***

### 故障排查

| 症状                                                                        | 可能原因                                                                                       | 解决方法                                                                                                                                                             |
| ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ConvaiManager.ActiveManager.Transcripts` 会引发 `InvalidOperationException` | 在 SDK 完成初始化之前访问                                                                            | 请使用 `manager.TryGetTranscripts(out var transcripts)` 而不要在早期阶段使用 `Transcripts` 属性，例如在 `OnEnable` 或 `Awake`                                                        |
| `GetTurns()` 会返回空列表                                                       | 尚不存在任何轮次，或者查询的 `IncludeActiveTurns` 为 `false` 而当前所有轮次仍处于活动状态                               | 省略 `TranscriptQuery`，或将 `IncludeActiveTurns = true` 设为包含进行中的轮次                                                                                                   |
| `Subscribe` 回调从未触发                                                        | 订阅得太晚，或者 `IncludeActive`/`IncludeTerminal` 排除了所有匹配的轮次                                      | 在 `ConnectAsync`之前或之后立即订阅；将 `ReplayExisting = true` 设为立即接收已有轮次                                                                                                   |
| `TranscriptTurn.StableText` 为空                                            | 轮次仍处于 `Streaming` 或 `Stable` 状态——只有轮次提交后，文本才会稳定                                            | 进行中内容的渲染请使用 `DisplayText` ，或者通过 `SubscribeCommitted`                                                                                                             |
| `订阅` 回调从未触发                                                               | `IncludeStreaming`/`IncludeFinal` 或说话人筛选条件排除了所有匹配的字幕，或者 `ReplayLatest` 为 `false` 且尚未收到新的字幕 | 检查 `IncludeStreaming`, `IncludeFinal`, `SpeakerType`, `SpeakerId`和 `ParticipantId` 上启用 `TranscriptCaptionSubscriptionOptions`；设置 `ReplayLatest = true` 以立即接收当前字幕 |

***

### 后续步骤

如需在不查询时间线的情况下响应事件驱动的转录内容，请使用 `ConvaiCharacterEventRelay` 或 `ConvaiTranscriptEventRelay` ——请参阅 [角色事件](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/character-events.md)。如需完整的角色脚本 API，请参阅 [角色与玩家 API](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/character-and-player-api.md)。如需查看 `ConvaiManager`上所有 facade 访问器的完整列表，请参阅 [ConvaiManager API](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/convaimanager-api.md).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/transcript-api.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
