MRが楽しい

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

HoloLens2でホロモンアプリを作る その101(MRTK3環境で音声入力のキーワードを設定する)

本日はアプリ作成枠です。
HoloLens2でホロモンアプリを作る進捗を書き留めていきます。

今回は MRTK3 環境で音声入力のキーワードを設定する改修を行いました。

MRTK3環境で音声入力のキーワードを設定する

MRTK3 環境では PhraseRecognitionSubsystem サブシステムから音声入力のキーワードが設定できます。
bluebirdofoz.hatenablog.com

CreateOrGetEventForPhrase 関数からキーワードとそれに対応するアクションを登録できます。
>|cs|// Get the first running phrase recognition subsystem.
// 最初に動作するフレーズ認識サブシステムを取得します。
var phraseRecognitionSubsystem = XRSubsystemHelpers.GetFirstRunningSubsystem();

// If we found one...
// 見つかった場合...
if (phraseRecognitionSubsystem != null)
{
// Register a phrase and its associated action with the subsystem.
// サブシステムにフレーズとそれに関連するアクションを登録する。
phraseRecognitionSubsystem.CreateOrGetEventForPhrase("your phrase").AddListener*1;
}
|

サンプルスクリプト

指定した音声入力のキーワードと対応するアクションを登録するサンプルスクリプトを作成しました。

SpeechCommandEvent 型で設定したキーワードとイベントをアプリ起動時に自動的に登録します。
これにより、音声入力でキーワードを検知すると直ちに設定したイベントが実行されます。
・SpeechCommandEvent.cs

using System;
using UnityEngine.Events;

namespace HoloMonApp.Content.XRPlatform.MRTK3
{
    [Serializable]
    public class SpeechCommandEvent
    {
        public string Keyword;

        public UnityEvent KickEvent;
    }
}

・SpeechInputHandlerMRTK3.cs

#if XRPLATFORM_MRTK3
using Microsoft.MixedReality.Toolkit;
using Microsoft.MixedReality.Toolkit.Subsystems;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

namespace HoloMonApp.Content.XRPlatform.MRTK3
{
    public class SpeechInputHandlerMRTK3 : MonoBehaviour
    {
        [SerializeField]
        private List<SpeechCommandEvent> p_SpeechCommandEventList;

        void Start()
        {
            // Get the first running phrase recognition subsystem.
            PhraseRecognitionSubsystem phraseRecognitionSubsystem = XRSubsystemHelpers.GetFirstRunningSubsystem<PhraseRecognitionSubsystem>();

            // If we found one...
            if (phraseRecognitionSubsystem != null)
            {
                foreach(SpeechCommandEvent speechCommandEvent in p_SpeechCommandEventList)
                {
                    string keyword = speechCommandEvent.Keyword;
                    UnityEvent kickEvent = speechCommandEvent.KickEvent;

                    // Register a phrase and its associated action with the subsystem
                    phraseRecognitionSubsystem.CreateOrGetEventForPhrase(keyword).AddListener(() => kickEvent.Invoke());
                }
            }
        }
    }
}
#endif

動作確認

シーンを再生してシミュレーションで「じゃんけん」キーワードを発声すると、ホロモンがじゃんけんのリアクションをしてくれました。

*1:) => Debug.Log("Phrase recognized"