
核心定义包附带有 KeywordRecognitionSubsystem,它是 MRTKSubsystem 和 IKeywordRecognitionSubsystem 的基本实现,作为负责 MRTK3 中的关键字/短语识别的子系统的基础。 MRTK 附带的具体实现(例如 WindowsKeywordRecognitionSubsystem),以及你可能构建的其他潜在短语识别子系统,都应该基于此类。 继承自 KeywordRecognitionSubsystem 的子系统可以使用 SpeechInteractor 基于可交互对象的设置触发选择事件 StatefulInteractable’s 。 继承的子类还允许将任意UnityAction’s注册到所选关键字 (keyword) ,以便在说出此类字词时调用操作。




var keywordRecognitionSubsystem = XRSubsystemHelpers.GetFirstRunningSubsystem<KeywordRecognitionSubsystem>();
if (keywordRecognitionSubsystem != null)
{
keywordRecognitionSubsystem.CreateOrGetEventForKeyword("your keyword").AddListener(() => Debug.Log("Keyword recognized"));
}using System.Collections.Generic;
using System.Linq;
using UnityEngine.Events;
using UnityEngine.Windows.Speech;
using UnityEngine;
using MixedReality.Toolkit.Subsystems;
using MixedReality.Toolkit;
public class KeywordManager : MonoBehaviour
{
//将此结构体暴露在Inspector面板中实现语音关键词和动作的添加
[System.Serializable]
public struct KeywordAndResponse
{
[Tooltip("关键字")]
public string Keyword;
[Tooltip("识别调用的UnityEvent")]
public UnityEvent Response;
}
public KeywordAndResponse[] KeywordsAndResponses;
private Dictionary<string, UnityEvent> responses;
void Start()
{
if (KeywordsAndResponses.Length > 0)
{
//将struct数组转换为字典,将struct中的Keyword转换为字典的关键字,UnityEven转换为字典的方法
responses = KeywordsAndResponses.ToDictionary(keywordAndResponse => keywordAndResponse.Keyword,
keywordAndResponse => keywordAndResponse.Response);
var keywordRecognitionSubsystem = XRSubsystemHelpers.GetFirstRunningSubsystem<KeywordRecognitionSubsystem>();
int Length = KeywordsAndResponses.Length;
for (int i = 0; i < Length; i++)
{
if (keywordRecognitionSubsystem != null)
{
//在子系统中注册一个关键字及其相关的操作
string Keyword = KeywordsAndResponses[i].Keyword;
keywordRecognitionSubsystem.CreateOrGetEventForKeyword(Keyword).AddListener
(() => { KeywordRecognizer_OnPhraseRecognized(Keyword); });
}
}
}
else
{
Debug.LogError("必须至少指定一个关键字 " + gameObject.name + ".");
}
}
//识别关键字之后的回调
private void KeywordRecognizer_OnPhraseRecognized(string Keyword)
{
// 如果识别到关键词就调用
if (responses.TryGetValue(Keyword, out UnityEvent keywordResponse))
{
keywordResponse.Invoke();
}
}
}