> 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-1/facial-expressions.md). Agents can also search and read this documentation through its [MCP server](https://docs.convai.com/api-docs/~gitbook/mcp).

# 面部表情

本部分提供关于在 Web 应用中使用 convai-web-sdk 集成和处理面部表情与口型同步的全面信息。

{% hint style="info" %}
:no\_entry: 此插件已弃用，不再提供支持。

\
如果你仍在使用旧版插件，我们建议切换到新版 Convai Web SDK： [链接](https://docs.convai.com/api-docs/plugins-and-integrations/web-plugins/convai-web-sdk)

\
仅供历史参考——这些文档已不再维护。
{% endhint %}

### 初始化

要启用面部表情功能，请使用必要参数初始化 `ConvaiClient` 。必须将 `enableFacialData` 标志设置为 `true` 才能启用面部表情数据。

```javascript
convaiClient.current = new ConvaiClient({
  apiKey: '<apiKey>',
  characterId: '<characterId>',
  enableAudio: true,
  enableFacialData: true,
  faceModel: 3, // OVR lipsync
});
```

{% hint style="info" %}
faceModel : 3 是标准配置，并且仍在积极维护。
{% endhint %}

### 接收 Viseme 数据

通过添加提供的回调函数来获取 viseme 数据。示例代码展示了如何处理和更新面部数据。

```javascript
const [facialData, setFacialData] = useState([]);
const facialRef = useRef([]);

convaiClient.current.setResponseCallback((response) => {
if (response.hasAudioResponse()) {
    let audioResponse = response?.getAudioResponse();
      if (audioResponse?.getVisemesData()?.array[0]) {
      //Viseme data
        let faceData = audioResponse?.getVisemesData().array[0];
        //faceData[0] implies sil value. Which is -2 if new chunk of audio is recieve.
          if (faceData[0] !== -2) {
            facialRef.current.push(faceData);
            setFacialData(facialRef.current);
          }
      }
}
```

### 调节形态目标

使用 `useFrame` 钩子（hook），它来自 `react-three-fiber` ，根据接收到的面部数据调节形态目标。

<pre class="language-javascript"><code class="lang-javascript"><strong>import {OvrToMorph} from 'convai-web-sdk'
</strong><strong>const blendShapeRef = useRef([]);
</strong>const currentBlendFrame = useRef(0);

useFrame((state, _delta) => {
 // Initiate blendshapes
    if(client?.facialData.length > 0){
// OvrToMorph is required for mapping reallusion morphs
    OvrToMorph(client?.facialData[currentBlendFrame.current],blendShapeRef);
    }
  if (currentBlendFrame.current &#x3C;= blendShapeRef?.current?.length) {
    // Logic to adjust morph targets based on facial data
    currentBlendFrame.current += 1;
  }
});
</code></pre>

除了面部表情之外， `convai-web-sdk` 还允许开发者调整特定面部特征的骨骼。接收 "Open\_Jaw"、"Tongue" 和 "V\_Tongue\_Out" 的骨骼调整值，并按照下方示例将其应用到角色上：

```javascript

// 如果当前 viseme 值为 Open_Jaw
characterRef.current.getObjectByName("CC_Base_JawRoot").setRotationFromEuler(jawRotation);
// 可以使用 THREE.lerp() 调整下颌旋转值。
// 示例
const jawRotation = new THREE.Euler(0,0,1.57);
// 此处 1.57 是下颌闭合时的基准值。
jawRotation.z = THREE.MathUtils.lerp(jawRotation.z,1.57 + blendShapeRef.current[currentBlendFrame.current-1][blend]*0.2,0.8);

```

{% hint style="info" %}
这些代码示例适用于 Reallusion 角色。
{% endhint %}

### 处理 100fps 动画

使用 [节流 ](https://www.geeksforgeeks.org/lodash-_-throttle-method/)，借助 lodash 确保动画在 100fps 下流畅运行。以下示例演示了如何保持动画帧率稳定。

```javascript
const throttledUpdate = _.throttle(updateAnimation, 10);
const [tick, setTick] = useState(true);

const updateAnimation = () => {
  setTick((tick) => {
    if (tick) {
      return tick;
    }
    return true;
  });
  requestAnimationFrame(throttledUpdate);
};

// 组件挂载时启动动画循环
useEffect(() => {
  requestAnimationFrame(throttledUpdate);
  // 组件卸载时清理动画循环
  return () => {
    cancelAnimationFrame(throttledUpdate);
  };
}, []);

// 使用帧钩子更新动画
useFrame((state, _delta) => {
  if (tick) {
    // 获取 viseme 数据并相应地调整变形目标的逻辑
    setTick(false);
  }
});
```

{% hint style="info" %}
注意：节流函数无法做到 100% 准确
{% endhint %}

### 处理 100fps 边界情况

节流精度可能导致边界情况。请设置时钟，并根据已用时间处理高于和低于 100fps 的情况。

```javascript
const [startClock, setStartClock] = useState(false);

useFrame((state, _delta) => {
  if (!startClock || !client?.isTalking) {
    state.clock.elapsedTime = 0;
    if (startClock) setStartClock(false);
  }
  if (client?.isTalking) {
    setStartClock(true);
  }
});

// 处理高于和低于 100fps 的情况
if (startClock) {
  if (Math.abs(Math.floor(state.clock.elapsedTime * 100) - currentBlendFrame.current) > 15) {
    if (Math.floor(state.clock.elapsedTime * 100) - currentBlendFrame.current > 0) {
      // 低于 100fps
           for(let i=0;i<15;i++){
              blendShapeRef.current.push(0)
            }
            currentBlendFrame.current += 15;
    } else {
      // 高于 100fps
       if(blendShapeRef.current.length > 15){
            blendShapeRef.current.splice(-15);
            currentBlendFrame.current -= 15;
       }
    }
  }
}


```


---

# 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-1/facial-expressions.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.
