> 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/api-can-kao/core-api-reference/live-apis-beta/audio-data-via-data-channel.md).

# 音频数据（通过数据通道）

本页解释了通过 WebRTC 数据通道发送给客户端的指标。

***

### 1. 在 Connect API 请求中启用音频数据

若要通过 WebRTC 数据通道接收音频，而不是使用标准音轨，请在调用 connect API 时配置 `audio_config` 。

**注意：** 通过数据通道传输音频数据仅支持 LiveKit 传输方式（默认）。

HTTP 请求：

```http
POST https://live.convai.com/connect
X-Api-Key: <X-Api-Key>
Content-Type: application/json
```

请求正文：

```json
{
  "character_id": "<your character_id>",
  "audio_config": {
    "output": {
      "audio_routing": "data_only",
      "max_chunk_duration_ms": 100,
      "add_wav_header": false
    }
  }
}
```

**配置字段：**

| 字段                           | 范围/选项                                                                                            | 说明                                                                                                                                                                    |
| ---------------------------- | ------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| audio\_routing（字符串）          | <p><code>"data\_only"</code></p><p><code>"audio\_only"</code> （默认）</p><p><code>"both"</code></p> | <p>控制音频传输方式：<br>• <code>"data\_only"</code> - 通过数据通道接收音频数据消息<br>• <code>"audio\_only"</code> - 使用标准 WebRTC 音轨（不接收音频数据消息）<br>• <code>"both"</code> - 同时通过音轨和数据通道接收</p> |
| max\_chunk\_duration\_ms（整数） | 10-1000，默认值为 100                                                                                 | 每个音频块的最大时长，单位为毫秒。数值向上取整至最接近的 10 毫秒（例如，95 毫秒 → 100 毫秒）                                                                                                                 |
| add\_wav\_header（布尔值）        | false（默认）/ true                                                                                  | 是否在每个音频块中包含 44 字节的 WAV 文件头（仅影响通过数据通道传输的音频）                                                                                                                            |

***

### 2. 在客户端接收音频数据

当 `audio_routing` 设置为 `"data_only"` 或 `"both"`.

音频数据会作为 RTVI 消息通过 WebRTC 数据通道发送。请使用以下条件筛选传入消息：

* `label === "rtvi-ai"`
* `type === "server-message"`
* `data.type === "audio-data"`

***

### 3. 音频数据消息结构

```json
{
  "label": "rtvi-ai",
  "type": "server-message",
  "data": {
    "type": "audio-data",
    "sample_rate": 24000,
    "channels": 1,
    "audio": "AAEAAg==...",
    "includes_wav_header": false
  }
}
```

**字段说明：**

| 字段                         | 类型  | 值/说明                                           |
| -------------------------- | --- | ---------------------------------------------- |
| `label`                    | 字符串 | 始终为 `"rtvi-ai"` （RTVI 协议标识符）                   |
| `type`                     | 字符串 | 始终为 `"server-message"` （RTVI 消息类型）             |
| `data.type`                | 字符串 | 始终为 `"audio-data"` （具体的消息子类型）                  |
| `data.sample_rate`         | 整数  | 音频采样率，单位为 Hz（例如 16000、24000、48000）             |
| `data.channels`            | 整数  | 音频声道数（1=单声道，2=立体声）                             |
| `data.audio`               | 字符串 | 经 Base64 编码的音频数据（原始 PCM 或带有标头的 WAV）            |
| `data.includes_wav_header` | 布尔值 | `true` 音频包含 44 字节 WAV 标头时使用， `false` 原始 PCM 使用 |
|                            |     |                                                |

**注意：**

* 每条消息包含一个音频块
* 音频块时长由 `max_chunk_duration_ms` 控制（默认值：100ms）
* 由于会四舍五入到最接近的 10ms，实际时长可能略长
* 音频数据是以 Base64 编码的 16 位有符号 PCM

***

#### 4. 音频数据格式与解码

| 字段         | 值                                | 备注                               |
| ---------- | -------------------------------- | -------------------------------- |
| 格式         | 16 位有符号 PCM（小端序）                 | 标准 PCM 音频格式                      |
| 编码         | Base64                           | 用于通过数据通道传输 JSON                  |
| 采样率        | 不固定（通常为 16000、24000 或 48000）     | 在 `sample_rate` 字段中指定            |
| 声道数        | 1（单声道）或 2（立体声）                   | 在 `channels` 字段                  |
| WAV 标头（可选） | 44 字节                            | 包含条件 `add_wav_header: true` 在配置中 |
| 块大小        | 由以下参数控制： `max_chunk_duration_ms` | 默认值为 100 毫秒，向上取整到最接近的 10 毫秒      |

**解码步骤：**

1. 对 `audio` 字段进行 Base64 解码以获取原始字节
2. 如果 `includes_wav_header` 为 `true`:
   * 前 44 个字节是 WAV 标头（可直接保存为 `.wav`)
   * 其余字节是 PCM 音频数据
3. 如果 `includes_wav_header` 为 `false`:
   * 所有字节都是原始的 16 位有符号 PCM 数据
   * 使用 `sample_rate` 和 `channels` 字段来配置音频上下文

#### 5. 接收和解码音频数据的示例代码

```javascript
import { Room, RoomEvent } from "livekit-client";

const CORE_SERVICE_BASE_URL = "https://live.convai.com";
const API_KEY = "<X-Api-Key>";
const CHARACTER_ID = "<your character_id>";

async function startVoiceSessionWithAudioData() {
  // 1) Call /connect with audio_config enabled
  const connectResp = await fetch(`${CORE_SERVICE_BASE_URL}/connect`, {
    method: "POST",
    headers: {
      "x-api-key": API_KEY,
      "content-type": "application/json",
    },
    body: JSON.stringify({
      character_id: CHARACTER_ID,
      audio_config: {
        output: {
          audio_routing: "data_only",
          max_chunk_duration_ms: 100,
          add_wav_header: false,
        },
      },
    }),
  });

  if (!connectResp.ok) {
    throw new Error(`/connect failed: ${connectResp.status}`);
  }

  const connectData = await connectResp.json();
  const { room_url, token, session_id } = connectData;

  // 2) 使用 room_url + token 加入 WebRTC 房间
  const room = new Room();

  // 3) 设置用于播放的音频上下文
  const audioContext = new AudioContext({ sampleRate: 48000 });
  const audioQueue = [];

  room.on(RoomEvent.Connected, () => {
    console.log("Connected to room");
  });

  room.on(RoomEvent.DataReceived, (payload) => {
    // LiveKit 数据负载是字节 -> 解码 -> 解析 JSON
    let msg;
    try {
      const text = new TextDecoder().decode(payload);
      msg = JSON.parse(text);
    } catch {
      return;
    }

    // 4) 仅筛选音频数据消息
    if (msg?.label !== "rtvi-ai") return;
    if (msg?.type !== "server-message") return;
    if (msg?.data?.type !== "audio-data") return;

    const audioData = msg.data;

    console.log("Received audio chunk:", {
      sample_rate: audioData.sample_rate,
      channels: audioData.channels,
      includes_wav_header: audioData.includes_wav_header,
      audio_length: audioData.audio.length,
    });

    // 5) 解码 base64 音频数据
    const base64Audio = audioData.audio;
    const binaryString = atob(base64Audio);
    const bytes = new Uint8Array(binaryString.length);
    for (let i = 0; i < binaryString.length; i++) {
      bytes[i] = binaryString.charCodeAt(i);
    }

    // 6) 转换为 AudioBuffer 并加入播放队列
    let pcmData = bytes;
    if (audioData.includes_wav_header) {
      // 跳过 WAV 头（前 44 个字节）
      pcmData = bytes.slice(44);
    }

    // 将字节转换为 16 位 PCM 采样值
    const samples = new Int16Array(
      pcmData.buffer,
      pcmData.byteOffset,
      pcmData.byteLength / 2,
    );

    // 转换为 Web Audio API 所需的 Float32Array
    const floatSamples = new Float32Array(samples.length);
    for (let i = 0; i < samples.length; i++) {
      floatSamples[i] = samples[i] / 32768.0; // 归一化到 [-1, 1]
    }

    // 创建 AudioBuffer
    const audioBuffer = audioContext.createBuffer(
      audioData.channels,
      floatSamples.length / audioData.channels,
      audioData.sample_rate,
    );
    audioBuffer.copyToChannel(floatSamples, 0);

    // 用于播放的队列
    audioQueue.push(audioBuffer);
    playNextChunk(); // 实现你自己的播放队列管理
  });

  room.on(RoomEvent.Disconnected, () => {
    console.log("Disconnected from room");
  });

  await room.connect(room_url, token);

  // 返回对象，以便调用方之后断开连接/清理
  return { room, session_id, audioContext };
}

// 使用示例：
startVoiceSessionWithAudioData().catch(console.error);
```

***

#### 6. 使用说明

通过数据通道传输音频数据适用于以下场景：

* **自定义音频处理** 在播放前（例如应用滤波器、效果或进行归一化）
* **自定义缓冲策略** 适用于网络状况不稳定的情况
* **录制/保存音频** 保存为 WAV 文件（需搭配 `add_wav_header: true`)
* **非浏览器客户端** 这些客户端不支持 WebRTC 音轨

对于基于浏览器的标准音频播放，建议使用默认设置 `audio_routing: "audio_only"` （标准 WebRTC 音轨），因为它延迟最低，且由浏览器自动处理。

***

## 代理指令：查询本文档

如果需要的信息在本页中没有直接提供，可以通过提问动态查询文档。

向当前页面 URL 发起 HTTP GET 请求，并附带 `ask` 查询参数：

```
GET https://docs.convai.com/api-docs/api-reference/core-api-reference/live-apis-beta/audio_data.md?ask=<question>
```

问题应具体、独立完整，并以自然语言编写。回复将包含问题的直接答案，以及文档中的相关摘录和来源。

当当前页面未明确提供答案、需要澄清或补充背景信息，或者想要获取相关文档章节时，请使用此机制。


---

# 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/api-can-kao/core-api-reference/live-apis-beta/audio-data-via-data-channel.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.
