> 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/lipsync-and-blendshape.md).

# 使用 blendshape 驱动面部动画

与角色语音一起流式传输 blendshape 帧，并将其应用到 3D 面部的 morph targets 上，使其嘴部随语音同步移动。

开启唇形同步后，Convai 会将面部混合变形帧与角色音频一同流式传输，然后将这些帧应用到 3D 模型的变形目标上。如果你使用 three.js 或其他 WebGL 引擎渲染自己的角色，请参阅本页。完成后，角色的嘴部会随语音同步运动，并在停止说话时恢复到中性状态。

### 前提条件

* 已安装 Convai Web SDK，并有一个可连接的客户端。请参阅 [Web SDK 快速入门](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/quickstart.md).
* 已加载到渲染器中、面部由变形目标驱动的 3D 模型。
* 模型的变形目标名称，以便将它们与流格式对应起来。

### 启用唇形同步

设置 `enableLipsync` 并在 `blendshapeConfig`中选择流格式。相同选项也适用于 `new ConvaiClient(...)` 来自 `@convai/web-sdk/core` 并转到 `useConvaiClient(...)` 来自 `@convai/web-sdk/react`.

```ts
import { ConvaiClient } from '@convai/web-sdk/core';

const client = new ConvaiClient({
  apiKey: 'YOUR_API_KEY',
  characterId: 'YOUR_CHARACTER_ID',
  enableLipsync: true,
  blendshapeConfig: {
    format: 'mha', // or 'arkit'
  },
});
```

当 `enableLipsync` 为 `true`时，SDK 会向 Convai 每次请求 10 帧混合形状数据，并将其缓冲到  `client.blendshapeQueue`。当其为  `false` 或被省略时，不会发送任何混合形状帧。

参数  `format`  决定每一帧的长度和顺序：

| `format`     | 帧长度 | 通道名称                                            |
| ------------ | --- | ----------------------------------------------- |
| `"mha"` （默认） | 251 | MetaHuman 控制项，例如 `CTRL_expressions_jawOpen`     |
| `"arkit"`    | 61  | 52 个 ARKit 混合形状，例如 `JawOpen`，然后是三个头部旋转值和六个眼部旋转值 |

两种格式的完整通道顺序见 [Blendshape 通道顺序参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/mappings-reference.md).

### 调整交付方式

`blendshapeConfig` 有三个交付选项。除非有实测依据需要调整，否则请保留默认值。

| 选项                       | 默认值                          | 效果                                                            |
| ------------------------ | ---------------------------- | ------------------------------------------------------------- |
| `deliver_chunks_ahead`   | `true` 当 `enableLipsync` 启用时 | Convai 会在音频播放前发送带索引的分块，因此队列会先缓存一段内容。设置 `false` 以回退到旧版的定速传输路径。 |
| `output_fps`             | `60`                         | 提前传输的分块的帧率。若 `deliver_chunks_ahead` 为 `false`.                |
| `frames_buffer_duration` | `0.1`                        | Convai 在随音频发送前累积的 blendshape 秒数。                              |

队列会按照分块元数据中携带的帧率播放帧；如果分块未携带帧率，则按每秒 60 帧播放。使用 `client.blendshapeQueue.getPlaybackFps()`.

### 从队列播放帧

在 `requestAnimationFrame`上运行一个循环。每次循环时，推进时间累加器，取出到期的帧，将最新一帧应用到面部，并从队列中移除这些帧。

```ts
let lastTime = 0;
let carryMs = 0;

function tick(now: number) {
  const queue = client.blendshapeQueue;

  // 中断会停止音频：立即将面部恢复为中性状态。
  if (queue.consumeNormalizationSignal()) {
    applyFrame(new Float32Array(frameLength));
    carryMs = 0;
  }

  const playing =
    queue.isBotSpeaking() || (queue.hasReceivedEndSignal() && queue.hasFrames());

  if (playing && queue.hasFrames()) {
    carryMs += lastTime ? now - lastTime : 0;
    const frameMs = 1000 / queue.getPlaybackFps();
    const due = Math.floor(carryMs / frameMs);
    if (due > 0) {
      const count = Math.min(due, queue.length);
      // 先读取再消耗：淡入淡出取决于已播放的帧数。
      const frame = queue.getFrameWithAlpha(count - 1);
      if (frame) applyFrame(frame);
      queue.consumeFrames(count);
      carryMs -= due * frameMs;
    }
  } else {
    carryMs = 0;
  }

  // 本轮已结束，所有预期帧均已播放。
  if (queue.isConversationEnded()) {
    queue.reset();
  }

  lastTime = now;
  requestAnimationFrame(tick);
}

requestAnimationFrame(tick);
```

`frameLength` 对于 `mha` 为 251，对于 `arkit`. `getFrameWithAlpha` 会让一轮开始时的前 10 帧淡入、结束时的后 10 帧淡出，避免嘴部突然张开或定格在某个形状。 `getFrame` 返回同一帧，但不应用淡入淡出效果。

{% hint style="warning" %}
不要将 `getFrameAtTime` 与 `consumeFrames`. `getFrameAtTime` 按经过的时间从队列前端索引，并且 `consumeFrames` 将队列前端向前移动，因此同时使用两者会使播放进度前进两次，导致嘴部动作超前于语音。
{% endhint %}

每个 `BlendshapeQueue` 方法都列在 [ConvaiClient 参考文档](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/convaiclient-core-api.md).

### 将帧应用到变形目标

如果模型的变形目标使用流中的通道名称，请在模型加载后构建一次槽位表，然后通过该表写入每一帧。无需映射器。

```ts
import { METAHUMAN_ORDER_251 } from '@convai/web-sdk/lipsync-helpers';
import type { Mesh } from 'three';

function bindFace(mesh: Mesh) {
  const slots = new Int32Array(METAHUMAN_ORDER_251.length).fill(-1);
  METAHUMAN_ORDER_251.forEach((name, i) => {
    const slot = mesh.morphTargetDictionary?.[name];
    if (slot !== undefined) slots[i] = slot;
  });

  return (frame: Float32Array) => {
    const influences = mesh.morphTargetInfluences;
    if (!influences) return;
    for (let i = 0; i < slots.length; i++) {
      if (slots[i] >= 0) influences[slots[i]] = frame[i] ?? 0;
    }
  };
}

const applyFrame = bindFace(faceMesh);
```

对于 `arkit`，使用 `ARKIT_ORDER_61` 替代 `METAHUMAN_ORDER_251`。两者均从 `@convai/web-sdk/lipsync-helpers`.

对于 `mha` 角色，还需应用 MetaHuman 骨架耦合，否则每次下颌张开时，嘴唇都会分开。 `createLipsyncProcessor('mha')` 会在一次调用中绑定网格、修复已知的名称混淆，并应用耦合、增益和淡化包络。请参阅 [应用 MetaHuman 限制驱动器](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/lipsync-and-blendshape/metahuman-limit-drivers-required-for-mha.md).

### 使用自定义映射器重新映射通道

如果变形目标使用不同的名称，请传入映射器。SDK 会在每帧进入队列时运行映射器。

```ts
import { createARKitNameMapper } from '@convai/web-sdk/lipsync-helpers';

const mapper = createARKitNameMapper({
  jawOpen: ['Jaw_Open'],
  eyeBlinkLeft: ['Eye_Blink_L'],
  eyeBlinkRight: ['Eye_Blink_R'],
  mouthSmileLeft: ['Mouth_Smile'],
  mouthSmileRight: ['Mouth_Smile'], // 与 mouthSmileLeft 求平均
});

const client = new ConvaiClient({
  apiKey: 'YOUR_API_KEY',
  characterId: 'YOUR_CHARACTER_ID',
  enableLipsync: true,
  blendshapeConfig: { format: 'arkit', customMapper: mapper },
});
```

`createMetaHumanNameMapper` 对 `mha`也能执行相同操作，映射键可以是完整的 `CTRL_expressions_*` 名称，也可以是简写（`jawOpen`）。格式中不存在的源名称会被跳过，并在控制台中发出警告。多个源映射到同一目标时，其值会取平均值。输出中只包含映射的目标。

第二个参数用于选择输出形状。两种形状都会为每一帧提供独立的值，并且在淡化过程中都会保留 `getFrameWithAlpha`:

| 输出              | 每个排队的帧                                   | 如何读取                                                                             |
| --------------- | ---------------------------------------- | -------------------------------------------------------------------------------- |
| `'object'` （默认） | A `Float32Array` 按目标顺序排列的目标值，并附带名称       | `getBlendshapeObject(frame)` 用于获取名称到值的对象                                         |
| `'optimized'`   | `{ names, values, nameToIndex, length }` | `frame.values[frame.nameToIndex.get('Jaw_Open')]`，或 `getBlendshapeObject(frame)` |

连接后若要更改映射器，请调用 `client.blendshapeQueue.setMapper(fn)`. `clearMapper()` 会恢复为原始帧，而 `hasMapper()` 会报告是否已设置映射器。

### 验证唇形同步

连接并发送一条消息，同时观察角色的面部。

{% hint style="success" %}
角色开始发声时，嘴部便开始动起来，跟随音节变化，并在声音停止后不到一秒内恢复中性状态。
{% endhint %}

如果面部始终不动，请确认 `enableLipsync` 为 `true` 并确认角色说话时 `client.blendshapeQueue.length` 会增加。如果帧已到达但面部仍然静止，则表示变形目标名称与格式不匹配：请记录 `mesh.morphTargetDictionary` 并与通道顺序参考进行比较。

### 后续步骤

{% content-ref url="/pages/c52240c5f5c86a00159cb30d9d04c5b6d5ea3c4a" %}
[应用 MetaHuman 限制驱动器](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/lipsync-and-blendshape/metahuman-limit-drivers-required-for-mha.md)
{% endcontent-ref %}

{% content-ref url="/pages/22ae6f4a7ad0727295a752b42c53546668e69c5a" %}
[在 React 中添加口型同步](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/react/real-time-lipsync.md)
{% endcontent-ref %}

{% content-ref url="/pages/e842433c402c6a1f2b7938d74b7fd4adf7da7152" %}
[在原生 TypeScript 中添加口型同步](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/real-time-lipsync.md)
{% endcontent-ref %}

{% content-ref url="/pages/4478f4a3cec9e37c9839b186fe7a71671f76fa3e" %}
[Blendshape 声道顺序参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/mappings-reference.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/lipsync-and-blendshape.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.
