#在Unity中使用语音识别及回调
##1.语音识别类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Windows.Speech;
using System;
public class ASPManager
{
private static ASPManager _instance;
public static Dictionary<string, SourceModel> dictSource = new Dictionary<string, SourceModel>();
public static ASPManager Instance
{
get
{
if (_instance == null)
{
_instance = new ASPManager();
}
return _instance;
}
}
public void Add(string str, MonoBehaviour mono, Action act = null)
{
_Add(str, mono, act,null);
}
public void Add(string str, MonoBehaviour mono, Action<object> actObj = null,object obj = null)
{
_Add(str, mono, null, actObj, obj);
}
void _Add(string str, MonoBehaviour mono, Action act = null, Action<object> actObj = null, object obj = null)
{
if (dictSource.ContainsKey(str))
{
Debug.LogError("输出 已经添加此输入重新覆盖 " + str);
dictSource.Remove(str);
_Add(str,mono, act, actObj);
return;
}
SourceModel sourceModel = new SourceModel();
//进行识别方法的注册
PhraseRecognizer m_phraseRecognizer = new KeywordRecognizer(new string[] { str });
m_phraseRecognizer.OnPhraseRecognized += sourceModel.M_PhraseRecognizer_OnPhraseRecognized;
m_phraseRecognizer.Start();
sourceModel.phraseRecognizer = m_phraseRecognizer;
sourceModel.actObj = actObj;
sourceModel.act = act;
sourceModel.mono = mono;
sourceModel.obj = obj;
dictSource.Add(str, sourceModel);
}
public void Removed(string str)
{
if (dictSource.ContainsKey(str))
{
dictSource[str].phraseRecognizer.Stop();
dictSource[str].phraseRecognizer.Dispose();
dictSource.Remove(str);
}
}
public void RemoveNowAll(MonoBehaviour mono)
{
List<string> lists = new List<string>();
foreach (var item in dictSource)
{
if(item.Value.mono == mono)
{
lists.Add(item.Key);
}
}
for (int i = 0; i < lists.Count; i++)
{
Removed(lists[i]);
}
}
}
public class SourceModel
{
public PhraseRecognizer phraseRecognizer { get; set; }
public Action<object> actObj { get; set; }
public Action act { get; set; }
public MonoBehaviour mono { get; set; }
public object obj { get; set; }
public void M_PhraseRecognizer_OnPhraseRecognized(PhraseRecognizedEventArgs args)
{
Debug.Log("输出 语音 " + args.text);
if (ASPManager.dictSource.ContainsKey(args.text))
{
if (actObj != null&& obj!=null)
{
actObj.Invoke(obj);
}
if (act != null)
{
act.Invoke();
}
}
}
}
##2.调用
不带参数
private void OnEnable()
{
ASPManager.Instance.Add("退出", this, ()=> { Debug.Log("test"); });
}
private void OnDisable()
{
ASPManager.Instance.RemoveNowAll(this);
}
带参数
private void OnEnable()
{
ASPManager.Instance.Add("测试", this, btnClick,0);
}
private void OnDisable()
{
ASPManager.Instance.RemoveNowAll(this);
}
private void btnClick(object index)
{
int num = (int)index;
Debug.Log("输出 " + num);
}