MRが楽しい

MRやVRについて学習したことを書き残す

公式チュートリアル「MR and Azure 301 7章」を試してみる

本日はチュートリアルの実施枠です。
Academyの「MR and Azure 301: Language translation」の実施内容をまとめます。
docs.microsoft.com
前回記事の続きです。
bluebirdofoz.hatenablog.com
今回は「Chapter 7」です。

Chapter 7:Call to Azure and translator service

最後に作成するスクリプトは Translator クラスです。
このクラスは以下を担当します。
・認証トークンと引き換えに、Azure でアプリケーションを認証する。
・認証トークンを使用して、翻訳するテキスト(MicrophoneManager クラスから受信)を送信します。
・翻訳結果を受け取って Results クラスに渡し、UIで視覚化します。

1.Script フォルダを開きます。
2.フォルダ内で右クリックして、Creapte -> C# Script を選択します。
Script の名称は Translator に設定します。
f:id:bluebirdofoz:20180809092712j:plain

3.新しいスクリプトをダブルクリックしてVisual Studioで開きます。
4-9.以下の通り、スクリプトを編集します。
・Translator.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// 名前空間の追加
using System;
using System.Collections;
using System.Xml.Linq;
using UnityEngine;
using UnityEngine.Networking;

public class Translator : MonoBehaviour {
    // メンバ変数の追加
    public static Translator instance;
    private string translationTokenEndpoint = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
    private string translationTextEndpoint = "https://api.microsofttranslator.com/v2/http.svc/Translate?";
    private const string ocpApimSubscriptionKeyHeader = "Ocp-Apim-Subscription-Key";

    //Substitute the value of authorizationKey with your own Key 
    //authorizationKeyの値を代入する
    private const string authorizationKey = "-InsertYourAuthKeyHere-";
    private string authorizationToken;

    // 言語を設定する
    // languages set below are: 
    // English 
    // French 
    // Italian 
    // Japanese 
    // Korean 
    // Translator Text API がサポートする60種類以上の言語の一覧は以下にあります
    // ・Supported languages in the Microsoft Translator Text API
    //   https://docs.microsoft.com/en-us/azure/cognitive-services/translator/languages
    public enum Languages { en, fr, it, ja, ko };
    public Languages from = Languages.en;
    public Languages to = Languages.it;
    
    // 初期化処理の追加
    private void Awake()
    {
        // Set this class to behave similar to singleton  
        // このクラスをシングルトンと同じように動作させます 
        instance = this;
    }

    // 初期化処理の追加(StartはAwakeの後に実行)  
    void Start()
    {
        // When the application starts, request an auth token 
        // アプリケーションが起動すると、認証トークンを要求する
        // ※ トークンは10分後に期限切れになります。
        //    アプリのシナリオに応じて、同じコルーチン呼び出しを複数回行う必要があります。
        StartCoroutine("GetTokenCoroutine", authorizationKey);
    }

    /// <summary> 
    /// Request a Token from Azure Translation Service by providing the access key. 
    /// Debugging result is delivered to the Results class. 
    /// Azure翻訳サービスからトークンを要求するには、アクセスキーを入力します。
    /// デバッグ結果はResultsクラスに渡されます。
    /// </summary> 
    private IEnumerator GetTokenCoroutine(string key)
    {
        if (string.IsNullOrEmpty(key))
        {
            throw new InvalidOperationException("Authorization key not set.");
        }

        using (UnityWebRequest unityWebRequest = UnityWebRequest.Post(translationTokenEndpoint, string.Empty))
        {
            unityWebRequest.SetRequestHeader("Ocp-Apim-Subscription-Key", key);
            yield return unityWebRequest.SendWebRequest();

            long responseCode = unityWebRequest.responseCode;

            // Update the UI with the response code 
            // 応答コードでUIを更新します
            Results.instance.SetAzureResponse(responseCode.ToString());

            if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError)
            {
                Results.instance.azureResponseText.text = unityWebRequest.error;
                yield return null;
            }
            else
            {
                authorizationToken = unityWebRequest.downloadHandler.text;
            }
        }

        // After receiving the token, begin capturing Audio with the MicrophoneManager Class
        // トークンを受け取った後、MicrophoneManagerクラスでAudioのキャプチャを開始します。 
        MicrophoneManager.instance.StartCapturingAudio();
    }

    /// <summary> 
    /// Request a translation from Azure Translation Service by providing a string.  
    /// Debugging result is delivered to the Results class. 
    /// 文字列を入力して、Azure翻訳サービスから翻訳を依頼してください。
    /// デバッグ結果はResultsクラスに渡されます。
    /// </summary> 
    public IEnumerator TranslateWithUnityNetworking(string text)
    {
        // This query string will contain the parameters for the translation 
        // このクエリ文字列には、翻訳のパラメータが含まれます。
        string queryString = string.Concat("text=", Uri.EscapeDataString(text), "&from=", from, "&to=", to);

        using (UnityWebRequest unityWebRequest = UnityWebRequest.Get(translationTextEndpoint + queryString))
        {
            unityWebRequest.SetRequestHeader("Authorization", "Bearer " + authorizationToken);
            unityWebRequest.SetRequestHeader("Accept", "application/xml");
            yield return unityWebRequest.SendWebRequest();

            if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError)
            {
                Debug.Log(unityWebRequest.error);
                yield return null;
            }

            // Parse out the response text from the returned Xml
            // 返されたXmlからの応答テキストを解析します。
            string result = XElement.Parse(unityWebRequest.downloadHandler.text).Value;
            Results.instance.SetTranslatedResult(result);
        }
    }
}

f:id:bluebirdofoz:20180809092727j:plain
※ 個人の環境に合わせて "-InsertYourAuthKeyHere-"の値を Chapter 1 で取得した Key 値に修正します。
bluebirdofoz.hatenablog.com

10.Visual Studio で変更を保存して Unity に戻ります。
f:id:bluebirdofoz:20180809092756j:plain


Chapter 7 はここまでです。
次回は Chapter 8 を実施します。
bluebirdofoz.hatenablog.com