> 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/web-plugins/convai-web-sdk/websocket-transport-layer.md).

# 使用 WebSocket 传输层

通过 WebSocket 而不是 WebRTC 连接 Convai 角色，注册传输，并在 React 或纯 TypeScript 中听到该角色的声音。

将 Convai Web SDK 会话从基于 LiveKit 的默认 WebRTC 传输切换为基于 Pipecat 的 WebSocket 传输。当你的部署环境无法使用 WebRTC，或你正在测试 WebSocket 路径时，请参阅此页面。

{% hint style="info" %}
在托管版 Convai 上使用 1.9.2 或更高版本。托管版 Convai 的 `/connect` 会返回一个 `ws://` URL，但此传输的端点仅接受 `wss://`。1.9.1 及更早版本无法连接，浏览器会报告关闭代码 `1006`。1.9.2 会在 `ws://` URL 或页面使用 https 时将 `wss://` 升级为 `/connect` ；本地 http 配置则会保留 `ws://`.
{% endhint %}

### 如何选择传输方式

`ConvaiConfig.transport` 可取值为 `"livekit"` （默认值）或 `"websocket"`。两种传输方式都会先向 Convai 发送相同的 `POST /connect` 请求。使用 `"websocket"`时，SDK 会从响应的 `room_url` 字段读取 WebSocket URL，并通过已注册的 WebSocket 会话建立连接。

WebSocket 会话并未内置于 `ConvaiClient`中。只有 `@convai/web-sdk/vanilla/websocket` 这个子路径会导入 Pipecat 包；导入它会产生副作用，将会话注册到 `ConvaiClient` 。从不导入此子路径的应用不会加载 Pipecat 代码。

### 安装 Pipecat 包

WebSocket 会话依赖两个 Pipecat 包。它们是 SDK 的可选 peer dependency，因此包管理器不会自动为你安装。请将它们与 SDK 一起添加：

```bash
npm install @convai/web-sdk @pipecat-ai/client-js @pipecat-ai/websocket-transport
```

如果没有这些包，导入 `@convai/web-sdk/vanilla/websocket` 会失败，并显示 `Could not resolve "@pipecat-ai/client-js"`.

### 注册传输方式并连接

在 `@convai/web-sdk/vanilla/websocket` 中导入一次，并确保在 `connect()` 运行前完成，然后设置 `transport: 'websocket'`。React 应用也要导入相同的子路径；此包没有专用于 React 的 WebSocket 入口点。

{% tabs %}
{% tab title="React" %}
{% code title="src/App.tsx" %}

```tsx
import '@convai/web-sdk/vanilla/websocket';
import { useConvaiClient } from '@convai/web-sdk/react';
import { ConvaiWidget } from '@convai/web-widget/react';

export default function App() {
  const client = useConvaiClient({
    apiKey: 'YOUR_API_KEY',
    characterId: 'YOUR_CHARACTER_ID',
    transport: 'websocket',
  });

  return <ConvaiWidget convaiClient={client} />;
}
```

{% endcode %}
{% endtab %}

{% tab title="TypeScript" %}
{% code title="src/main.ts" %}

```typescript
import '@convai/web-sdk/vanilla/websocket';
import { ConvaiClient } from '@convai/web-sdk/vanilla';

const client = new ConvaiClient({
  apiKey: 'YOUR_API_KEY',
  characterId: 'YOUR_CHARACTER_ID',
  transport: 'websocket',
});

await client.connect();
```

{% endcode %}
{% endtab %}
{% endtabs %}

### 播放角色的语音

传输方式会负责播放语音，无需额外接线。Pipecat 的 WebSocket 传输会通过自带的 Web Audio 播放器，将角色音频直接播放到扬声器；无论使用 React 还是纯 TypeScript 都一样。上面的示例已完整可用，无需 `AudioRenderer` 且没有 `botAudioTrack` 监听器。

&#x20;`botAudioTrack` 事件不会在此传输方式下触发。Pipecat 传输方式只公开本地麦克风轨道，因此没有可供附加的角色轨道。你从旧代码中保留的任何 `botAudioTrack` 监听器或 `AudioRenderer` 都无妨；它们永远不会收到轨道。

要让角色静音，请调用 `setCharacterMuted(true)`。在 WebSocket 传输方式下，需要使用 1.9.2 或更高版本；静音期间生成的语音会被丢弃，而不会排队等待。请参阅 [将角色语音静音](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/mute-the-characters-voice.md).

### 麦克风行为

不同传输方式的麦克风默认状态不同：

| 传输方式          | 调用 `connect()`                                                           |
| ------------- | ------------------------------------------------------------------------ |
| `"livekit"`   | 默认关闭，除非 `startWithAudioOn` 为 `true`.                                     |
| `"websocket"` | 默认开启，因为 Pipecat 会话会在 `connect()`期间初始化音频流。当 `startWithAudioOn` 为 `false`. |

在 WebSocket 传输方式下， `connect()` 始终会请求麦克风权限——即使设置了 `startWithAudioOn: false` ——并且在用户响应浏览器提示之前不会返回。Pipecat 每次初始化时都会打开录音器，因此 WebSocket 会话必然会触发权限提示。请先通过用户操作请求访问权限，再进行连接。如果要在完全不使用麦克风的情况下进行文本交互，请使用 SSE 传输方式。

仅在页面可能于连接后立即开始监听时，才在 WebSocket 传输方式下将 `startWithAudioOn` 留空。在此传输方式下，通过 `audioControls` 静音会禁用本地音频轨道，因此 Convai 接收到的是静音。

### 与 LiveKit 传输方式的区别

| 行为             | `"livekit"`                                                             | `"websocket"`                                                                               |
| -------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| `uploadFile()` | 支持                                                                      | 不支持。此功能需要 LiveKit 房间，否则会抛出 `[ConvaiClient] uploadFile: not connected to a LiveKit room` 错误。 |
| 就绪信号超时         | `error` 事件会触发，并携带 `bot-ready not received within 45000ms` 如果角色始终未发出就绪信号 | 无超时；WebSocket 会话会自行报告就绪状态。                                                                  |
| 机器人音频          | 通过房间播放，由 `AudioRenderer` 或 `ConvaiWidget`                               | 由 Pipecat 传输本身播放； `botAudioTrack` 不会触发                                                      |
| 触发 `botReady`  | 在我们的测试中约为 4 到 7 秒                                                       | 在我们的测试中约为 17 到 21 秒                                                                         |
| 视觉帧            | 发布到房间的视频轨道                                                              | 仅当 `enableVideo` 为 `true` 且 `visionInputConfig.enabled` 不为 `false`                          |
| `client.room`  | 已连接的 LiveKit 房间                                                         | 存在但从未连接                                                                                     |

### 故障排查

#### 由于未注册传输，连接失败

**症状：** `connect()` 因以下错误而拒绝：

```
[ConvaiClient] WebSocket transport is not registered. Add `import '@convai/web-sdk/vanilla/websocket'` before calling connect().
```

**原因：** 配置设置了 `transport: 'websocket'`，但没有导入模块 `@convai/web-sdk/vanilla/websocket`.

**解决方法：** 将副作用导入添加到一个会在 `connect()` 运行之前加载的模块中。

**验证：** `connect()` 成功完成，并且 `botReady` 触发。

#### 缺少 WebSocket URL 时连接失败

**症状：** `connect()` 因以下内容而拒绝 `No WebSocket URL returned from /connect endpoint (expected room_url)`.

**原因：** Convai 返回了一个 `/connect` 响应，但其中没有 `room_url`.

**修复方法：** 请检查 `url` 选项是否指向支持 WebSocket 传输的 Convai 实时端点，或者移除 `url` 以使用默认值。

**验证：** `connect()` 调用成功。

#### 连接在 connect 期间关闭

**症状：** `connect()` 调用失败，并显示 `WebSocket disconnected before connect completed`.

**原因：** WebSocket 在传输层报告连接成功之前就已关闭。

**修复方法：** 重试连接，并检查是否有网络规则阻止了发往 Convai 的 WebSocket 流量。

**验证：** `connect()` 调用成功。

#### 托管版 Convai 上的连接以代码 1006 关闭

**症状：** WebSocket 在 connect 期间关闭，浏览器报告的关闭代码为 `1006`.

**原因：** 1.9.1 及更早版本会打开托管版 Convai 返回的 `ws://` URL，而该端点只接受 `wss://`.

**修复方法：** 将 `@convai/web-sdk` 升级到 1.9.2 或更高版本。

**验证：** `connect()` 成功完成，并且 `botReady` 触发。

### 后续步骤

{% content-ref url="/pages/1ef8009eea712d4c41fd7a2a07e473a277395698" %}
[处理错误和断开连接](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/error-handling.md)
{% endcontent-ref %}

{% content-ref url="/pages/8c6e3631e7e7da5b3c9acf5a0019d7737dc79e19" %}
[Web SDK 事件参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/event-reference.md)
{% endcontent-ref %}

{% content-ref url="/pages/dff296725774f9173a7391e28344f5f94cf35b60" %}
[配置和类型参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/best-practices-and-type-definitions.md)
{% endcontent-ref %}


---

# 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/web-plugins/convai-web-sdk/websocket-transport-layer.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.
