文档

支持

Vivox Unity SDK

Vivox Unity SDK

在 C# 脚本中使用 Audio Tap

How to add Audio Taps through C# scripts.
阅读时间3 分钟最后更新于 13 天前

本节介绍如何通过脚本而不是通过编辑器 UI 添加 Audio Tap。

Capture Source Tap 和 Channel Audio Tap

您可以通过 C# 脚本将 Capture Source Tap 和 Channel Audio Tap 添加到场景中。以下示例说明了如何通过脚本为 Vivox Channel Audio Tap 音频添加回声效果:
private GameObject _channelAudioGameObject;public void AddChannelAudioEffect(){ // Create the GameObject _channelAudioGameObject = new GameObject("ChannelAudioGameObject"); // Add the Tap to it _channelAudioGameObject.AddComponent<VivoxChannelAudioTap>(); // Also add an echo filter, for example _channelAudioGameObject.AddComponent<AudioEchoFilter>();}
创建一个空游戏对象,然后添加
VivoxChannelAudioTap
和 Unity 提供的
AudioEchoFilter
,以便为所有音频应用回声。您可以切换示例中用于
VivoxCaptureSourceTap
的 Audio Tap,而无需针对不同的用例进行任何更改。

Participant Tap 脚本

通过 VivoxParticipant 的类
CreateVivoxParticipantTap
方法可以在脚本中轻松创建 Participant Tap。通过订阅
VivoxService.Instance.ParticipantAddedToChannel
消息,每当参与者加入频道时,您都会收到回调。然后,您可以在提供的 VivoxParticipant 对象上调用
CreateVivoxParticipantTap
,这将为新参与者创建一个包含 Vivox Participant Tap 的游戏对象,以便为特定参与者获取音频。
以下示例演示如何订阅
ParticipantAddedToChannel
并为每个新频道参与者添加回声效果。
using Unity.Services.Vivox;using UnityEngine;public class ParticipantHandler : MonoBehaviour{ void Start() { VivoxService.Instance.ParticipantAddedToChannel += AddParticipantEffect; } void AddParticipantEffect(VivoxParticipant participant) { var gameObject = participant.CreateVivoxParticipantTap("MyNewGameObject"); gameObject.AddComponent<AudioEchoFilter>(); }}
请注意,上面的示例脚本不会删除创建的对象。如果需要,可添加逻辑以仅为特定频道成员创建 Tap。 使用
CreateVivoxParticipantTap
方法创建的 Vivox Participant Tap 游戏对象的生命周期与 VivoxParticipant 生命周期相关联。这意味着当参与者离开频道或本地玩家注销时,该游戏对象将自动销毁。也可以通过调用
VivoxParticipant.DestroyVivoxParticipantTap
来显式销毁任何 Vivox 参与者的 Participant Tap。

监控 Audio Tap 状态

Audio Tap 具有公开的参数 TapId 可用于监控创建的 Audio Tap 的状态。创建 Tap 后,TapId 的值应大于或等于零,这意味着没有错误。以下是创建 Tap 并确保 TapId 具有预期值的示例:
private GameObject _channelAudioGameObject;public void AddChannelAudioEffect(){ // Create the GameObject _channelAudioGameObject = new GameObject("ChannelAudioGameObject"); // Add the Tap to it var tap = _channelAudioGameObject.AddComponent<VivoxChannelAudioTap>(); if (tap.TapId < 0) { Destroy(_channelAudioGameObject); // Destroy the GameObject, since the status is not valid Debug.LogError($"Failed to create VivoxChannelAudioTap"); return; } else { Debug.Log("There was no error creating VivoxChannelAudioTap"); }}
如果 TapId 小于零,则其值可用于排查错误。以下是可能的值及其错误原因:
  • -1 :此 Tap 当前未注册。当 Tap 已实例化但尚未注册到 Vivox 时,便是这种情况。例如,由于正在等待自动获取频道,可能导致这种情况。
  • -1010 :此 Tap 未注册。
  • -1011 :此 Tap 试图使用无效的参与者名称进行注册。
  • -1012 :此 Tap 试图使用无效的频道名称进行注册。
  • -1050 :仅适用于 Vivox Participant Tap。从提供的参与者名称中找不到参与者 URI。
  • -1051 :此 Tap 试图注册到 Vivox,但 VivoxService 未初始化。确保在初始化 Audio Tap 之前初始化 VivoxService。
  • -1052 :此 Tap 试图使用无效的频道名称注册到 Vivox。确保正确设置频道名称。