> 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/convai-unity-sdk/scripting-reference/audio-api.md).

# 音频 API

Unity SDK 中通过脚本控制麦克风静音、各角色的音频输出以及解锁播放的参考文档。

`ConvaiAudio` 是 `ConvaiManager`上的音频门面，提供对麦克风采集、各角色远程音频输出和音频播放解锁的脚本化控制。它清晰地划分了职责：麦克风输入（发送给 Convai 的内容）、角色音频输出（从角色处听到的内容）以及 WebGL 音频播放门控。

**访问方式：** `ConvaiManager.ActiveManager.Audio`

```csharp
var audio = ConvaiManager.ActiveManager?.Audio;
if (audio == null) return; // manager not yet bootstrapped
```

***

### 麦克风控制

#### 属性

| 属性                       | 类型     | 说明                                         |
| ------------------------ | ------ | ------------------------------------------ |
| `IsMicMuted`             | `bool` | 麦克风静音且未向 Convai 发送音频时为 True                |
| `RequiresUserGesture`    | `bool` | 音频播放因等待用户交互而被阻止时为 True（仅限 WebGL）           |
| `IsAudioPlaybackActive`  | `bool` | 音频播放当前处于活动状态且已解锁时为 True                    |
| `CanEnableAudioPlayback` | `bool` | 当 `EnableAudioPlayback()` 可以调用以解锁音频时为 True |

#### 方法

| 方法                                                                             | 返回                       | 说明                  |
| ------------------------------------------------------------------------------ | ------------------------ | ------------------- |
| `SetMicMuted(bool muted)`                                                      | `void`                   | 显式设置麦克风静音状态         |
| `ToggleMicMuted()`                                                             | `bool`                   | 切换麦克风静音状态。返回新的静音状态。 |
| `StartListeningAsync(int microphoneIndex = 0, CancellationToken ct = default)` | `IConvaiOperation<Unit>` | 在指定的设备索引上开始采集麦克风音频  |
| `StopListeningAsync(CancellationToken ct = default)`                           | `IConvaiOperation<Unit>` | 停止采集麦克风音频           |

microphoneIndex `microphoneIndex` 参数 `StartListeningAsync` 对应于以下方法返回的设备列表中的索引： `IMicrophoneDeviceService.GetAvailableDevices()`。使用 `ConvaiManager.ActiveManager.TryGetMicrophoneDeviceService(out var svc)` 可按名称枚举设备，然后选择索引。索引 `0` 表示使用系统默认麦克风。

#### 事件

| 事件                 | 签名             | 触发时机                                  |
| ------------------ | -------------- | ------------------------------------- |
| `OnMicMuteChanged` | `Action<bool>` | 麦克风静音状态发生变化时触发。参数：新的静音状态（true = 已静音）。 |

```csharp
using Convai.Runtime.Facades;
using UnityEngine;

public class MicMuteIndicator : MonoBehaviour
{
    [SerializeField] private GameObject _muteIcon;

    private void OnEnable()
    {
        var audio = ConvaiManager.ActiveManager?.Audio;
        if (audio == null) return;
        audio.OnMicMuteChanged += OnMuteChanged;
        _muteIcon.SetActive(audio.IsMicMuted);
    }

    private void OnDisable()
    {
        var audio = ConvaiManager.ActiveManager?.Audio;
        if (audio != null)
            audio.OnMicMuteChanged -= OnMuteChanged;
    }

    private void OnMuteChanged(bool isMuted) => _muteIcon.SetActive(isMuted);
}
```

***

### 按角色控制音频

这些方法用于控制是否在本地播放特定角色的音频输出。请使用以下来源中的角色 ID： `ConvaiCharacter.CharacterId` 或 `ConvaiManager.ActiveManager.Characters`.

| 方法                                                        | 返回     | 说明                                  |
| --------------------------------------------------------- | ------ | ----------------------------------- |
| `SetCharacterMuted(string characterId, bool muted)`       | `bool` | 设置特定角色的静音状态。如果更改已应用，则返回 `true` 。    |
| `MuteCharacter(string characterId)`                       | `bool` | 将特定角色的音频输出设为静音。如果已应用，则返回 `true` 。   |
| `UnmuteCharacter(string characterId)`                     | `bool` | 取消特定角色音频输出的静音。如果已应用，则返回 `true` 。    |
| `IsCharacterMuted(string characterId)`                    | `bool` | 如果 `true` 角色的音频输出当前处于静音状态，则返回       |
| `SetRemoteAudioEnabled(string characterId, bool enabled)` | `bool` | 启用或禁用某个角色的远程音频输出。如果已应用，则返回 `true` 。 |
| `IsRemoteAudioEnabled(string characterId)`                | `bool` | 如果 `true` 此角色的远程音频输出已启用，则返回         |

{% hint style="info" %}
**静音与远程音频启用状态：** 这是两种独立的控制方式。远程音频启用/禁用控制 SDK 是否为该角色传输音频输出。静音则控制通过本地音频输出设备播放接收的音频。禁用远程音频可节省带宽；静音仅是本地音量控制。
{% endhint %}

#### 事件

| 事件                            | 签名                     | 触发时机                                      |
| ----------------------------- | ---------------------- | ----------------------------------------- |
| `OnRemoteAudioEnabledChanged` | `Action<string, bool>` | 角色的远程音频启用状态发生变化。参数：characterId、isEnabled。 |

***

### 音频播放 — WebGL

在 WebGL 中，浏览器会阻止音频播放，直到用户与页面进行交互。SDK 会根据此要求限制音频输出。

| 成员                       | 类型     | 说明                                   |
| ------------------------ | ------ | ------------------------------------ |
| `RequiresUserGesture`    | `bool` | 音频因等待用户交互而被阻止时为 True                 |
| `CanEnableAudioPlayback` | `bool` | 可调用 `EnableAudioPlayback()` 时为 True  |
| `IsAudioPlaybackActive`  | `bool` | 音频播放已解锁并处于活动状态时为 True                |
| `EnableAudioPlayback()`  | `void` | 解锁音频播放。 **必须在用户手势处理程序中调用** （例如按钮点击）。 |

{% hint style="danger" %}
在 WebGL 上，调用 `EnableAudioPlayback()` 如果不在用户手势处理程序中（例如，在 `Start()` 或 `OnEnable()`中）就不会生效——浏览器会阻止解锁。将其绑定到 UI 按钮的 `onClick` 事件，或在 `OnPointerClick`.
{% endhint %}

```csharp
using Convai.Runtime.Facades;
using UnityEngine;
using UnityEngine.UI;

public class WebGLStartButton : MonoBehaviour
{
    [SerializeField] private Button     _startButton;
    [SerializeField] private GameObject _startPanel;

    private void OnEnable()  => _startButton.onClick.AddListener(OnStartClicked);
    private void OnDisable() => _startButton.onClick.RemoveListener(OnStartClicked);

    private void OnStartClicked()
    {
        var audio = ConvaiManager.ActiveManager?.Audio;
        if (audio == null) return;

        // 在用户手势中解锁音频
        if (audio.CanEnableAudioPlayback)
            audio.EnableAudioPlayback();

        // 连接并开始聆听
        ConvaiManager.ActiveManager.EnableAudioAndStartListening();

        _startPanel.SetActive(false);
    }
}
```

***

### 使用示例

#### 示例 1 — 训练模拟 HUD 中的静音按钮

军事训练模拟程序在 HUD 中提供了一个按键式麦克风静音按钮，让受训者可以在与观察员交谈前将自己静音，而不必断开连接。

```csharp
using Convai.Runtime.Facades;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class MuteButton : MonoBehaviour
{
    [SerializeField] private Button   _button;
    [SerializeField] private TMP_Text _label;

    private void OnEnable()
    {
        _button.onClick.AddListener(OnClicked);
        var audio = ConvaiManager.ActiveManager?.Audio;
        if (audio != null)
        {
            audio.OnMicMuteChanged += RefreshLabel;
            RefreshLabel(audio.IsMicMuted);
        }
    }

    private void OnDisable()
    {
        _button.onClick.RemoveListener(OnClicked);
        var audio = ConvaiManager.ActiveManager?.Audio;
        if (audio != null)
            audio.OnMicMuteChanged -= RefreshLabel;
    }

    private void OnClicked() => ConvaiManager.ActiveManager?.Audio?.ToggleMicMuted();

    private void RefreshLabel(bool isMuted) =>
        _label.text = isMuted ? "取消静音" : "静音";
}
```

#### 示例 2 — 多 NPC 评估场景中按角色切换音频

企业入职培训模拟程序中有两位 AI 讲师。评估管理器脚本会在主讲师进行评估的环节静音副讲师，随后再恢复两位讲师的声音。

```csharp
using Convai.Runtime.Components;
using Convai.Runtime.Facades;
using System.Collections;
using UnityEngine;

public class AssessmentAudioManager : MonoBehaviour
{
    [SerializeField] private ConvaiCharacter _primaryInstructor;
    [SerializeField] private ConvaiCharacter _secondaryInstructor;

    public void BeginPrimaryEvaluation()
    {
        var audio = ConvaiManager.ActiveManager?.Audio;
        if (audio == null) return;

        // 静音副讲师，只播放主讲师的声音
        audio.MuteCharacter(_secondaryInstructor.CharacterId);
        audio.UnmuteCharacter(_primaryInstructor.CharacterId);
    }

    public void RestoreBothInstructors()
    {
        var audio = ConvaiManager.ActiveManager?.Audio;
        if (audio == null) return;

        audio.UnmuteCharacter(_primaryInstructor.CharacterId);
        audio.UnmuteCharacter(_secondaryInstructor.CharacterId);
    }
}
```

#### 示例 3 — 连接前选择麦克风设备

交互式体验允许用户在会话开始前从下拉菜单中选择首选麦克风，然后开始使用所选设备进行监听。

```csharp
using Convai.Runtime.Facades;
using System.Collections.Generic;
using TMPro;
using UnityEngine;

public class MicrophoneSelector : MonoBehaviour
{
    [SerializeField] private TMP_Dropdown _dropdown;

    private List<string> _deviceNames = new();

    private void Start()
    {
        var manager = ConvaiManager.ActiveManager;
        if (manager == null || !manager.TryGetMicrophoneDeviceService(out var svc)) return;

        _deviceNames.Clear();
        _dropdown.ClearOptions();

        foreach (var device in svc.GetAvailableDevices())
        {
            _deviceNames.Add(device.Name);
            _dropdown.options.Add(new TMP_Dropdown.OptionData(device.Name));
        }

        _dropdown.RefreshShownValue();
    }

    public async void OnConfirmDevice()
    {
        int index = _dropdown.value;
        var audio = ConvaiManager.ActiveManager?.Audio;
        if (audio == null) return;

        await audio.StartListeningAsync(index, destroyCancellationToken);
        Debug.Log($"Listening on: {_deviceNames[index]}");
    }
}
```

***

### 故障排查

| 症状                                        | 可能原因                                           | 解决方法                                                                                                                 |
| ----------------------------------------- | ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| WebGL 上没有音频输出                             | `EnableAudioPlayback()` 未在用户手势操作中调用            | 将 `EnableAudioPlayback()` 绑定到按钮的 `onClick`事件；不要在 `Start()` 或 `Awake()`                                               |
| `ToggleMicMuted()` 返回 `true` 但角色仍能听到玩家的声音 | `IsMicMuted` 控制 SDK 的静音状态——请确认角色会话已连接且音频管线正在运行 | 检查 `IsSessionConnected` 是否在当前角色上为真；静音仅在会话期间生效                                                                        |
| `MuteCharacter()` 返回 `false`              | 无法识别角色 ID——该角色可能尚未注册                           | 确认 ID 与 `ConvaiCharacter.CharacterId`一致；该角色必须位于 `ConvaiManager.Characters`                                           |
| `StartListeningAsync` 在移动设备上失败            | 未获得平台麦克风权限                                     | 使用 `TryGetPermissionService` 在调用前请求麦克风权限 `StartListeningAsync`                                                       |
| `IsRemoteAudioEnabled` 返回 `false` 连接后     | `EnableRemoteAudioOnStart` 在角色上为 `false`       | 在 Inspector 中将 `ConvaiCharacter.EnableRemoteAudioOnStart = true` 设为 true，或在会话开始后调用 `character.EnableRemoteAudio()` 。 |

***

### 后续步骤

有关角色级音频事件和会话控制，请参阅 [角色与玩家 API](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/character-and-player-api.md)。有关 WebGL 特定的音频要求和限制，请参阅 [WebGL 平台指南](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/platform-guides/webgl.md)。有关连接和会话控制，请参阅 [ConvaiManager API](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/convaimanager-api.md).


---

# 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/convai-unity-sdk/scripting-reference/audio-api.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.
