Windows语音转文字

Unity官方手册:Windows.Speech.DictationRecognizer

支持中英文语音识别,目前仅在Win10平台测试成功,Win11未测试。

前置条件:

  • 在windows设置里,找到"隐私"→“语音”,勾选"在线语音识别"。

语音识别代码:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using UnityEngine.Windows.Speech;
 
public class DictationScript : MonoBehaviour
{
    public Text hypothesesText;//显示输入过程中猜想结果的
    public Text recognitionsText;//显示识别结果的
    public Button startBtn;
    public Button stopBtn;
 
    private DictationRecognizer dictationRecognizer;
 
    void Start()
    {
        dictationRecognizer = new DictationRecognizer();
 
        dictationRecognizer.DictationResult += OnDictationResult;
        dictationRecognizer.DictationHypothesis += OnDictationHypothesis;
        dictationRecognizer.DictationComplete += OnDictationComplete;
        dictationRecognizer.DictationError += OnDictationError;
 
        //dictationRecognizer.Start();
        startBtn.onClick.AddListener(DictationStart);
        stopBtn.onClick.AddListener(DictionStop);
    }
 
    private void OnDestroy()
    {
        dictationRecognizer.Stop();
        dictationRecognizer.Dispose();
    }
 
    /// <summary>
    /// 语音识别结果
    /// </summary>
    /// <param name="text">识别结果</param>
    /// <param name="confidence"></param>
    private void OnDictationResult(string text, ConfidenceLevel confidence)
    {
        Debug.LogFormat("识别结果: {0}", text);
        recognitionsText.text = text;
 
        DictionStop();//我是希望得到结果就自动停止输入
    }
 
    /// <summary>
    /// 语音输入过程中对结果猜想时触发的事件。
    /// </summary>
    /// <param name="text">识别猜想</param>
    private void OnDictationHypothesis(string text)
    {
        Debug.LogFormat("识别猜想: {0}", text);
        hypothesesText.text = text;
    }
 
    private void OnDictationComplete(DictationCompletionCause cause)
    {
        if (cause != DictationCompletionCause.Complete)
            Debug.LogErrorFormat("识别失败: {0}.", cause);
    }
 
    private void OnDictationError(string error, int hresult)
    {
        Debug.LogErrorFormat("识别错误: {0}; HResult = {1}.", error, hresult);
    }
 
    /// <summary>
    /// 开启听写识别会话
    /// </summary>
    public void DictationStart()
    {
        dictationRecognizer.Start();
        startBtn.gameObject.SetActive(false);
        stopBtn.gameObject.SetActive(true);
    }
 
    /// <summary>
    /// 结束听写识别会话
    /// </summary>
    public void DictionStop()
    {
        dictationRecognizer.Stop();
        startBtn.gameObject.SetActive(true);
        stopBtn.gameObject.SetActive(false);
    }
 
}