# Vivox Unity SDK クイックスタートガイド

> Follow this workflow to get started with Vivox voice and text chat.

Unity では、ゲーム開発者が自己ホスティング型ソリューションに投資することなく、チャンネルスタイルのワークフローを通じてユーザー間の音声通信とテキスト通信を提供するための手段として、Vivox サービスを提供しています。

Unity のマルチプレイヤー通信用の音声およびテキストチャットサービスは、マネージドホスティング型のソリューションによって、音声チャットとダイレクトメッセージテキストサービスを提供します。

ゲームに接続してプロジェクトの設定を行うことで、すぐにプロジェクトに通信を追加できます。2D および 3D チャンネル内のユーザーを何人でも接続できます。ユーザーが音量の制御、ミュートアクションの実行、チャンネルの管理を行えるようにしたり、ユーザーをチームチャットに参加させたり、ユーザーを複数のチャンネルに参加させたりできます。

## Unity プロジェクト内で Vivox サービスを有効にする##enable-the-vivox-service-in-a-unity-project

Unity Dashboard で Unity プロジェクトに Vivox の音声とテキストを設定するには、以下の手順を実行します。

1. Unity Dashboard ([https://cloud.unity3d.com](https://cloud.unity3d.com/)) でアカウントとプロジェクトを作成します。

2. 左ペインで、**Products** (製品) を選択します。**Communication & Safety** (コミュニケーションと安全性) で、**Vivox Voice and Text Chat** を選択します。

3. オンボーディングのステップに従います。オンボーディングプロセス中に、プロジェクトで使用する Vivox API 認証情報が設定されます。

## Unity プロジェクトを Vivox に接続する##connect-your-unity-project-to-vivox

Unity プロジェクトを Vivox に接続するには、以下の手順を実行します。

1. ローカル Unity プロジェクトを作成するか開きます。

2. エディターで、**Window > Package Manager > Search Unity Registry** (ウィンドウ > パッケージマネージャー > Unity Registry を検索) を選択します。

3. Vivox を検索します。Install (インストール) を選択します。

4. **Edit > Project Settings > Services** (編集 > プロジェクト設定 > サービス) を選択し、プロジェクトに正しいプロジェクト ID が関連付けられていることを確認します。

5. **Service** (サービス) で、**Vivox** を選択し、正しい認証情報がプロジェクトにプルされていることを確認します。

   > **Note:**
   >
   > manifest.json ファイルを編集するか、Package Manager を使用 (**Window > Package Manager > + > Add package by name** (ウィンドウ > パッケージマネージャー > + > 名前でパッケージを加える) を選択し、`com.unity.services.vivox` を名前として使用) して、必要なパッケージを直接追加することができます。詳細については、[プロジェクトマニフェスト](https://docs.unity3d.com/Manual/upm-manifestPrj.html) に関する Unity ドキュメントを参照してください。

## ライフサイクルのアクション##lifecycle-actions

### Initialize##initialize

Unity Authentication Services を使用するときは、Vivox パッケージによって認証情報とトークンが自動的に処理されます。

```cs
using System;
using UnityEngine;
using Unity.Services.Authentication;
using Unity.Services.Core;
using Unity.Services.Vivox;

async void InitializeAsync()
{
    await UnityServices.InitializeAsync();
    await AuthenticationService.Instance.SignInAnonymouslyAsync();

    await VivoxService.Instance.InitializeAsync();
}
```

### サインイン##sign-in

Vivox SDK を初期化した後で、VivoxService を使用してログインできます。

> **Note:**
>
> `LoginOptions` を [`VivoxService.Instance.LoginAsync(LoginOptions options = null)`](https://docs.unity3d.com/Packages/com.unity.services.vivox@latest/index.html?subfolder=/api/Unity.Services.Vivox.IVivoxService.html#Unity_Services_Vivox_IVivoxService_LoginAsync_Unity_Services_Vivox_LoginOptions_) に渡して、EnableTTS や DisplayName などの値を設定できます。

```cs
 using Unity.Services.Vivox;

public async void LoginToVivoxAsync()
{
    LoginOptions options = new LoginOptions();
    options.DisplayName = UserDisplayName;
    options.EnableTTS = true;
    await VivoxService.Instance.LoginAsync(options);
}
```

### エコーチャンネルに参加する##join-an-echo-channel

サインインした後、[`VivoxService.Instance.JoinEchoChannelAsync(string channelName, ChatCapability chatCapability, ChannelOptions channelOptions = null)`](https://docs.unity3d.com/Packages/com.unity.services.vivox@latest/index.html?subfolder=/api/Unity.Services.Vivox.IVivoxService.html#Unity_Services_Vivox_IVivoxService_JoinEchoChannelAsync_System_String_Unity_Services_Vivox_ChatCapability_Unity_Services_Vivox_ChannelOptions_) を使用してエコーチャンネルに参加し、Vivox をローカルでテストすることができます。

```cs
 using Unity.Services.Vivox;

public async void JoinEchoChannelAsync()
{
    string channelToJoin = "Lobby";
    await VivoxService.Instance.JoinEchoChannelAsync(channelToJoin, ChatCapability.TextAndAudio);
}
```

> **Note:**
>
> チャンネルは最初の参加リクエストが送信された時点で作成されます。

エコーチャンネルで自分の声が聞こえることを確認したら、ポジショナルチャンネルまたはグループチャンネルに参加して他の参加者の声を聞くことができます。[`VivoxService.Instance.JoinGroupChannelAsync((string channelName, ChatCapability chatCapability, ChannelOptions channelOptions = null))`](https://docs.unity3d.com/Packages/com.unity.services.vivox@latest/index.html?subfolder=/api/Unity.Services.Vivox.IVivoxService.html#Unity_Services_Vivox_IVivoxService_JoinGroupChannelAsync_System_String_Unity_Services_Vivox_ChatCapability_Unity_Services_Vivox_ChannelOptions_) と [`VivoxService.Instance.JoinPositionalChannelAsync(string channelName, ChatCapability chatCapability, Channel3DProperties positionalChannelProperties, ChannelOptions channelOptions = null)`](https://docs.unity3d.com/Packages/com.unity.services.vivox@latest/index.html?subfolder=/api/Unity.Services.Vivox.IVivoxService.html#Unity_Services_Vivox_IVivoxService_JoinPositionalChannelAsync_System_String_Unity_Services_Vivox_ChatCapability_Unity_Services_Vivox_Channel3DProperties_Unity_Services_Vivox_ChannelOptions_) を使用すると、グループチャンネルとポジショナルチャンネルにそれぞれ参加できます。[Channel3DProperties](https://docs.unity3d.com/Packages/com.unity.services.vivox@latest/index.html?subfolder=/api/Unity.Services.Vivox.Channel3DProperties.html) は、会話が可能な距離やオーディオフェードモデルなどのポジショナルチャンネル固有の値を渡すために使用できる構造体です。

オプションとして、ユーザーがどのチャンネルに参加できるかのアクセス制御をより厳密に行う必要がある場合は、[Vivox アクセストークン (VAT)](./access-token-guide/access-token-guide-toc.md) をチャンネル参加フローに統合できます。

> **Note:**
>
> チャンネル名は、さまざまなチャンネルタイプ全体で一意である必要があります。

### 音声/テキストチャンネルから退出する##leave-a-voice-and-text-channel

チャンネルからユーザーを削除するには、[`VivoxService.Instance.LeaveChannelAsync(string channelName)`](https://docs.unity3d.com/Packages/com.unity.services.vivox@latest/index.html?subfolder=/api/Unity.Services.Vivox.IVivoxService.html#Unity_Services_Vivox_IVivoxService_LeaveChannelAsync_System_String_) または [`VivoxService.Instance.LeaveAllChannels()`](https://docs.unity3d.com/Packages/com.unity.services.vivox@latest/index.html?subfolder=/api/Unity.Services.Vivox.IVivoxService.html#Unity_Services_Vivox_IVivoxService_LeaveAllChannelsAsync) を使用します。複数のチャンネルから個別に退出できる場合は、それらのチャンネル名を検索可能な場所に保存する必要があります。

```cs
 using Unity.Services.Vivox;

public async void LeaveEchoChannelAsync()
{
    string channelToLeave = "Lobby";
    await VivoxService.Instance.LeaveChannelAsync(channelToLeave);
}
```

詳細については、[チャンネルから退出する](./developer-guide/channels/leave-channel.md) を参照してください。

### ユーザーをサインアウトする##sign-out-a-user

ユーザーをサインアウトするには、[`VivoxService.Instance.LogoutAsync()`](https://docs.unity3d.com/Packages/com.unity.services.vivox@latest/index.html?subfolder=/api/Unity.Services.Vivox.IVivoxService.html#Unity_Services_Vivox_IVivoxService_LogoutAsync) メソッドを呼び出します。ユーザーがサインアウトされると、Vivox SDK とのネットワークトラフィックの送受信がなくなります。これは一般的に、アプリケーションを終了するときや、ユーザーがアプリ内で別のアカウントにサインインできるシナリオで、そのユーザーをゲームサーバーからサインアウトするときにのみ呼び出します。

```cs
using Unity.Services.Vivox;

public async void LogoutOfVivoxAsync ()
{
    VivoxService.Instance.LogoutAsync;
}
```

詳細については、[ゲームからサインアウトする](./developer-guide/vivox-unity-sdk-basics/sign-in-with-custom-id.md) を参照してください。

## チャンネル内のアクション##in-channel-actions

### 参加者イベントを処理する##handle-participant-events

Vivox SDK は、ユーザーが参加しているチャンネルに対して新しいプレイヤーの追加または削除が行われるたびにイベントを送信します。これらのイベントには以下のようにサブスクライブできます。

* [`VivoxService.Instance.ParticipantAddedToChannel`](https://docs.unity3d.com/Packages/com.unity.services.vivox@latest/index.html?subfolder=/api/Unity.Services.Vivox.IVivoxService.html#Unity_Services_Vivox_IVivoxService_ParticipantAddedToChannel)
* [`VivoxService.Instance.ParticipantRemovedFromChannel`](https://docs.unity3d.com/Packages/com.unity.services.vivox@latest/index.html?subfolder=/api/Unity.Services.Vivox.IVivoxService.html#Unity_Services_Vivox_IVivoxService_ParticipantRemovedFromChannel)

このイベントは、`VivoxParticipant` タイプのオブジェクトによって起動されます。このオブジェクトには、チャンネルに参加した時点の参加者の `DisplayName`、`PlayerId`、`AudioEnergy` などの重要な情報が含まれます。変更可能な値 (`SpeechDetected, IsMuted`、および A`udioEnergy`) に対する変更をゲームに警告するためのイベントが存在します。これらのイベントは以下のとおりです。

* [`VivoxParticipant.ParticipantMuteStateChanged`](https://docs.unity3d.com/Packages/com.unity.services.vivox@latest/index.html?subfolder=/api/Unity.Services.Vivox.VivoxParticipant.html#Unity_Services_Vivox_VivoxParticipant_ParticipantMuteStateChanged)
* [`VivoxParticipant.ParticipantSpeechDetected`](https://docs.unity3d.com/Packages/com.unity.services.vivox@latest/index.html?subfolder=/api/Unity.Services.Vivox.VivoxParticipant.html#Unity_Services_Vivox_VivoxParticipant_ParticipantSpeechDetected)
* [`VivoxParticipant.ParticipantAudioEnergyChanged`](https://docs.unity3d.com/Packages/com.unity.services.vivox@latest/index.html?subfolder=/api/Unity.Services.Vivox.VivoxParticipant.html#Unity_Services_Vivox_VivoxParticipant_ParticipantAudioEnergyChanged)

```cs
using Unity.Service.Vivox;

List<RosterItem> rosterList = new List<RosterItem>();

private void BindSessionEvents(bool doBind)
{
    if(doBind)
    {
        VivoxService.Instance.ParticipantAddedToChannel += onParticipantAddedToChannel;
        VivoxService.Instance.ParticipantRemovedFromChannel += onParticipantRemovedFromChannel;
    }
    else
    {
        VivoxService.Instance.ParticipantAddedToChannel -= onParticipantAddedToChannel;
        VivoxService.Instance.ParticipantRemovedFromChannel -= onParticipantRemovedFromChannel;
    }
}

private void onParticipantAddedToChannel(VivoxParticipant participant)
{
    ///RosterItem is a class intended to store the participant object, and reflect events relating to it into the game's UI.
    ///It is a sample of one way to use these events, and is detailed just below this snippet.
    RosterItem newRosterItem = new RosterItem();
    newRosterItem.SetupRosterItem(participant);
    rosterList.Add(newRosterItem);
}

private void onParticipantRemovedFromChannel(VivoxParticipant participant)
{
    RosterItem rosterItemToRemove = rosterList.FirstOrDefault(p => p.Participant.PlayerId == participant.PlayerId);
    rosterList.Remove(rosterItemToRemove);
}
```

以下のコードスニペットは、`RosterItem` が取りうる構造をさらに詳しく示しています。

```cs
 using Unity.Service.Vivox;
using UnityEngine;

public class RosterItem : MonoBehaviour
{
    public VivoxParticipant Participant;
    public Text PlayerNameText;

    public Image ChatStateImage;
    public Sprite MutedImage;
    public Sprite SpeakingImage;
    public Sprite NotSpeakingImage;

    public SetupRosterItem(VivoxParticipant participant)
    {
        Participant = participant;
        PlayerNameText.text = Participant.DisplayName;
        UpdateChatStateImage();
        Participant.ParticipantMuteStateChanged += UpdateChatStateImage;
        Participant.ParticipantSpeechDetected += UpdateChatStateImage;
    }

    private void UpdateChatStateImage()
    {
        /// Update the UI of the game to the state of the participant
        if (Participant.IsMuted)
        {
            ChatStateImage.sprite = MutedImage;
            ChatStateImage.gameObject.transform.localScale = Vector3.one;
        }
        else
        {
            if (Participant.SpeechDetected)
            {
                ChatStateImage.sprite = SpeakingImage;
                ChatStateImage.gameObject.transform.localScale = Vector3.one;
            }
            else
            {
                ChatStateImage.sprite = NotSpeakingImage;
            }
        }
    }
}
```

詳細については、[参加者のイベント](./developer-guide/channels/participant-events.md) を参照してください。

### チャンネルにテキストメッセージを送信する##send-text-messages-to-a-channel

ゲームが参加しているチャンネルでテキストが有効になっている場合、ユーザーはグループテキストメッセージを送受信できます。メッセージを送信するために、ゲームは [`VivoxService.Instance.SendChannelTextMessageAsync(string channelName, string message)`](https://docs.unity3d.com/Packages/com.unity.services.vivox@latest/index.html?subfolder=/api/Unity.Services.Vivox.IVivoxService.html#Unity_Services_Vivox_IVivoxService_SendChannelTextMessageAsync_System_String_System_String_Unity_Services_Vivox_MessageOptions_) メソッドを使用します。この SDK 呼び出しが行われると、そのチャンネルにいる他のユーザーは `ChannelMessageReceived` イベントを受信します。このイベントは `VivoxMessage` 値を返します。この値には、メッセージの送信者、テキスト、およびメッセージが送信されたチャンネルが含まれています。

```cs
using Unity.Service.Vivox;

private async void SendMessageAsync(string channelName, string message)
{
    VivoxService.Instance.SendChannelTextMessageAsync(channelName, message);
}

private void BindSessionEvents(bool doBind)
{
    VivoxService.Instance.ChannelMessageReceived += onChannelMessageReceived;
}

private void onChannelMessageReceived(VivoxMessage message)
{
    string messageText = message.MessageText;
    string senderID = message.SenderPlayerId;
    string senderDisplayName = message.SenderDisplayName;
    string messageChannel = message.ChannelName;
}
```

詳細については、[グループテキストメッセージを送受信する](./developer-guide/messaging/channel-messages.md) を参照してください。

### 他の参加者をミュートする##mute-other-participants

ローカルミュートを使用すると、特定のユーザーに対して他のユーザーをミュートできます。[`VivoxParticipant.MutePlayerLocally()`](https://docs.unity3d.com/Packages/com.unity.services.vivox@latest/index.html?subfolder=/api/Unity.Services.Vivox.VivoxParticipant.html#Unity_Services_Vivox_VivoxParticipant_MutePlayerLocally) 関数を使用すると、ユーザーにはミュートされたユーザーの声が聞こえなくなりますが、チャンネル内の他のユーザーには引き続きミュートされたユーザーの声が聞こえます。ユーザーのミュートを解除するには [`VivoxParticipant.UnmutePlayerLocally()`](https://docs.unity3d.com/Packages/com.unity.services.vivox@latest/index.html?subfolder=/api/Unity.Services.Vivox.VivoxParticipant.html#Unity_Services_Vivox_VivoxParticipant_UnmutePlayerLocally) を使用します。通常、これらのコマンドは、チャンネルの特定の参加者に対して参加時に関連付けられた UI 要素にアタッチされる必要があります。

例えば、Cynthia、Fernando、Wang がチャンネル内にいるとします。Fernando は Wang の声を聞きたくありません。ローカルミュートを使用すると、Wang の声が Fernando に聞こえなくなるように設定できます。ただし、Cynthia には引き続き Wang の声が聞こえ、Wang には引き続き Cynthia と Fernando の声が聞こえます。

```cs
{
if (participant.InAudio && setMute)
{
    participant.MutePlayerLocally
}
else if (participant.InAudio)
{
    participant.UnmutePlayerLocally
}
else
{
    //Tell player to try again
    Debug.Log("Try Again");
}
}
```

詳細については、[特定のユーザーに対して他のユーザーをミュートする](./developer-guide/muting/mute-other-users.md) を参照してください。

### 自分をミュートする##mute-yourself

ユーザーのマイクをミュートするためのメソッドには、`AudioInputDevices` と `SetTransmissionMode()` の 2 つがあります。この 2 つのメソッドが役立つシナリオはそれぞれ異なります。

[`Transmission.None`](https://docs.unity3d.com/Packages/com.unity.services.vivox@latest/index.html?subfolder=/api/Unity.Services.Vivox.TransmissionMode.html) を使用して、どのチャンネルでもプレイヤーの声が聞こえないようにすることもできます。例を次に示します。

```cs
await VivoxService.Instance.SetChannelTransmissionModeAsync(Transmission.None, channelName)
```

詳細については、[ユーザーのマイクをミュートする](./developer-guide/muting/mute-user-microphone.md) を参照してください。

## 次のステップ##next-steps

基本的なチャットが機能するようになったら、追加のツールを使用して Vivox の機能を拡張できます。

* [テキストチャット](./text-chat-guide/text-chat-guide-overview.md) を充実させる機能を追加します。
* [音声認識](./developer-guide/speech-to-text/_index.md) などのアクセシビリティ機能を検討します。
* その他のトピックと機能については、[開発者ガイド](./developer-guide/_index.md) を参照してください。
