> 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/react/real-time-lipsync.md).

# 实时口型同步

支持的格式

## ARKit（61 个元素）

苹果的 ARKit blendshape 格式，包含 52 个面部 blendshapes + 9 个旋转值：

* 52 个标准面部 blendshape（眼睛、眉毛、下颌、嘴巴、脸颊、鼻子）
* 3 个头部旋转值（俯仰、偏航、翻滚）
* 6 个眼部旋转值（左/右眼注视）

## MetaHuman（251 个元素）

Unreal Engine 的 MetaHuman 格式，包含 251 个 CTRL\_expressions\_\* blendshapes：

* 全面的面部控制（眉毛、眼睛、脸颊、鼻子、嘴巴、下颌）
* 高度精细的嘴型，用于精准口型同步
* 高保真角色动画的行业标准

## 配置选项

### ConvaiConfig（useConvaiClient）

```typescript
interface ConvaiConfig {
  // ... 其他选项
  
  /**
   * 启用 lipsync/面部动画 blendshape（默认：false）。
   * 启用后，以 60fps 流式传输实时 blendshape 数据。
   */
  enableLipsync?: boolean;
  
  /**
   * 从服务器接收的 blendshape 格式（默认：'mha'）。
   * 'arkit' - 61 个元素（52 个 blendshape + 9 个旋转值）
   * 'mha' - 251 个元素（MetaHuman 格式）
   */
  blendshapeFormat?: 'arkit' | 'mha';
}
```

### 包含所有选项的示例

```tsx
const convaiClient = useConvaiClient({
  apiKey: '你的-api-key',
  characterId: '你的-character-id',
  enableVideo: true,
  enableLipsync: true,
  blendshapeFormat: 'arkit',
  startWithVideoOn: false,
});
```

## 访问 Blendshape 队列

blendshape 队列可在客户端实例上使用：

```tsx
import { useConvaiClient } from '@convai/web-sdk';
import { useEffect, useRef } from 'react';
import * as THREE from 'three';
import { useGLTF } from '@react-three/drei';

function CharacterController() {
  const convaiClient = useConvaiClient({<ConvaiConfig>});
  const characterRef = useRef<THREE.SkinnedMesh | null>(null);
  const startTimeRef = useRef<number>(0);
  const { scene } = useGLTF('/character.glb');
  
  useEffect(() => {
    // 在加载的模型中查找面部 SkinnedMesh
    scene.traverse((child) => {
      if (child instanceof THREE.SkinnedMesh && child.morphTargetInfluences) {
        if (child.name.toLowerCase().includes('head') || 
            child.name.toLowerCase().includes('face') ||
            child.morphTargetInfluences.length > 50) {
          characterRef.current = child;
        }
      }
    });
  }, [scene]);
  
  // 跟踪机器人何时开始说话
  useEffect(() => {
    const unsubscribe = convaiClient.on('speakingChange', (isSpeaking: boolean) => {
      if (isSpeaking) {
        startTimeRef.current = performance.now();
      }
    });
    
    return unsubscribe;
  }, [convaiClient]);
  
  useEffect(() => {
    if (!convaiClient.state.isConnected) return;
    
    let animationId: number;
    
    const animate = () => {
      const queue = convaiClient.blendshapeQueue;
      
      if (queue.hasFrames() && queue.isConversationActive()) {
        // 计算机器人开始说话以来经过的时间
        const elapsedTime = (performance.now() - startTimeRef.current) / 1000;
        
        // 根据经过时间获取帧（与音频同步）
        const result = queue.getFrameAtTime(elapsedTime);
        
        if (result && characterRef.current?.morphTargetInfluences) {
          applyBlendshapesToCharacter(result.frame, characterRef.current.morphTargetInfluences);
        }
      }
      
      animationId = requestAnimationFrame(animate);
    };
    
    animate();
    
    return () => cancelAnimationFrame(animationId);
  }, [convaiClient.state.isConnected]);
  
  return <primitive object={scene} />;
}

// 辅助函数：将 blendshape 应用到角色
function applyBlendshapesToCharacter(frame: Float32Array, influences: number[]) {
  const maxIndex = Math.min(frame.length, influences.length);
  for (let i = 0; i < maxIndex; i++) {
    influences[i] = frame[i];
  }
}
```


---

# 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/react/real-time-lipsync.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
