using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Windows.Speech; using ZXKFramework; /// 语音命令识别 public class SpeechRecognition : MonoBehaviour { // 短语识别器 private PhraseRecognizer m_PhraseRecognizer; // 关键字 string[] keywords; // 可信度 public ConfidenceLevel m_confidenceLevel = ConfidenceLevel.Medium; public static SpeechRecognition Instance; public static event Action callBack; private void Start() { Instance = this; DontDestroyOnLoad(this); callBack = null; } /// /// 关闭之后 只能接收到小智小智 /// public void Close() { OnDestroy(); TheStart(); } /// /// 命令数据刷新2 /// public void Open(string[] newKeys) { OnDestroy(); List list = new List(); for (int i = 0; i < newKeys.Length; i++) { if (!string.IsNullOrEmpty(newKeys[i])) { list.Add(newKeys[i]); } } keywords = list.ToArray(); TheStart(); } /// /// 命令数据刷新 /// public void Open() { OnDestroy(); string data = Resources.Load("VoiceCommand").text; if (!string.IsNullOrEmpty(data)) { List loAllData = new List(); string[] loData = data.Split('|'); foreach (var item in loData) { if (!string.IsNullOrEmpty(item)) { loAllData.Add(item.Trim()); } } keywords = new string[loAllData.Count]; for (int i = 0; i < loAllData.Count; i++) { keywords[i] = loAllData[i]; } } TheStart(); } void TheStart() { if (m_PhraseRecognizer == null) { //创建一个识别器 m_PhraseRecognizer = new KeywordRecognizer(keywords, m_confidenceLevel); //通过注册监听的方法 m_PhraseRecognizer.OnPhraseRecognized += M_PhraseRecognizer_OnPhraseRecognized; //开启识别器 m_PhraseRecognizer.Start(); } } /// 当识别到关键字时,会调用这个方法 private void M_PhraseRecognizer_OnPhraseRecognized(PhraseRecognizedEventArgs args) { _SpeechRecognition(args.text); print(args.text); } private void OnDestroy() { //判断场景中是否存在语音识别器,如果有,释放 if (m_PhraseRecognizer != null) m_PhraseRecognizer.Dispose(); } /// 识别到语音的操作 void _SpeechRecognition(string msg) { callBack?.Invoke(msg); } }