最近一直在弄一个实时语音识别的功能,上网查资料的时候才发现unity现在已经有了自带的语音识别的接口

https://docs.unity3d.com/2019.3/Documentation/ScriptReference/Windows.Speech.DictationRecognizer.html

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Windows.Speech;

public class SpeechRecognition : MonoBehaviour
{

    DictationRecognizer dictationRecognizer;


    // Use this for initialization
    void Start()
    {
        dictationRecognizer = new DictationRecognizer();

        dictationRecognizer.DictationResult += onDictationResult;
        dictationRecognizer.DictationHypothesis += onDictationHypothesis;
        dictationRecognizer.DictationComplete += onDictationComplete;
        dictationRecognizer.DictationError += onDictationError;

        dictationRecognizer.Start();
    }

    private void OnDisable()
    {
        dictationRecognizer.DictationResult -= onDictationResult;
        dictationRecognizer.DictationHypothesis -= onDictationHypothesis;
        dictationRecognizer.DictationComplete -= onDictationComplete;
        dictationRecognizer.DictationError -= onDictationError;

        dictationRecognizer.Stop();
    }


    //该事件在用户说话时暂停时触发,通常是在句子的最后。将在这里返回完整的识别字符串。
    void onDictationResult(string text, ConfidenceLevel confidence)
    {
        Debug.LogFormat( text);
    }

    //此事件在用户说话时连续触发。当识别器侦听时,它将为此提供文本。
    void onDictationHypothesis(string text)
    {
        Debug.LogFormat(text);
    }

    //当听写识别器停止时触发此事件。识别程序可以通过调用stop()方法、超时或遇到任何错误来停止。
    //超时条件:
    //如果识别器启动且5秒钟内没有侦听任何内容,它将超时。
    //如果识别器给出了结果,然后它在20秒内不监听任何内容,它将超时。
    void onDictationComplete(DictationCompletionCause cause)
    {
        if (cause != DictationCompletionCause.Complete)
            Debug.LogErrorFormat("停止", cause);
    }

    //当发生错误时将触发此事件。
    void onDictationError(string error, int hresult)
    {
        Debug.LogErrorFormat("错误", error, hresult);
    }
}


然后美滋滋的运行
在这里插入图片描述
看了一下大概提示是没有语音权限之类的。从隐私里面打开设置。

在这里插入图片描述
打开设置,不过有些W10版本跟我的显示不太一样,反正就是隐私-语音 然后打开

再次运行
在这里插入图片描述
有效果了,完美。

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐