Unity 文字转语音,一种用Window自带的微软语音识别(应该只支持Win10以上),一种是用百度语音识别,也可以考虑其他平台的SDK。
- Window 自带的微软语音识别
参考官方手册:Windows.Speech.DictationRecognizer - Unity 脚本 API (unity3d.com)
这个中英识别都比较准确,不过应该只支持Win10以上。
需在设置里开启在线语音识别。
代码部分:
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);
}
}
中英识别都不错,不过只支持Window,百度的这个我也没测试其他平台,自行测试吧。