前言
Unity中文字转语音需要用到
interop.speechlib.dll
和CustomMarshalers.dll
插件
将这两个插件放到Plugins
目录下
再将SpeechManager.cs
导入到项目中
通过调用Speak(string strInfo)
进行播放文字语音
通过调用StopSpeak()
进行暂停语音播放
SpeechManager.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Windows.Speech;
using SpeechLib;
public static class SpeechContent
{
public const string Wake = "醒醒醒醒,能听到我说话吗";
public const string AskWhere = "你现在在哪里";
public const string RaiseLeg = "抬一下左腿";
public const string StartCure = "开始救治";
public const string CreatInjuryTicket = "生成伤票";
}
public class SpeechManager : MonoBehaviour
{
public static SpeechManager Instance { get; private set; }
/// <summary>
/// 语音识别成功后执行的回调
/// </summary>
public Action<string> SpeechActions;
private KeywordRecognizer keywordRecognizer;
private string[] Keywords_array;
private SpVoice spv;
private void Awake()
{
Instance = this;
InitSpeech();
InitSpVoice();
}
/// <summary>
/// 初始化语音转文字
/// </summary>
private void InitSpVoice()
{
spv = new SpVoice();
//找到kangkang作为与语音
for (int i = 0; i < spv.GetVoices().Count; i++)
{
Debug.Log(spv.GetVoices().Item(i).GetDescription());
if (spv.GetVoices().Item(i).GetDescription().Contains("Huihui"))
{
spv.Voice = spv.GetVoices().Item(i);
Debug.Log("设置语音 " + spv.GetVoices().Item(i).GetDescription());
}
}
spv.Volume = 100;
}
/// <summary>
/// 初始化语音识别
/// </summary>
private void InitSpeech()
{
Keywords_array = new string[3];
Keywords_array [0] = SpeechContent.Wake;
Keywords_array [1] = SpeechContent.AskWhere;
Keywords_array [2] = SpeechContent.RaiseLeg;
keywordRecognizer = new KeywordRecognizer(Keywords_array);
keywordRecognizer.OnPhraseRecognized += OnKeywordsRecognized;
keywordRecognizer.Start ();
}
private void OnKeywordsRecognized(PhraseRecognizedEventArgs args)
{
Debug.Log ("Keyword: " + args.text + "; Confidence: " + args.confidence + "; Start Time: " + args.phraseStartTime + "; Duration: " + args.phraseDuration);
SpeechActions?.Invoke(args.text);
}
public void Speak(string content)
{
spv.Speak(string.Empty,SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak);
spv.Speak(content, SpeechVoiceSpeakFlags.SVSFlagsAsync);
}
/// <summary>
/// 暂停播报
/// </summary>
public void StopSpeak()
{
spv.Speak(string.Empty,SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak);
}
private void OnDestroy()
{
spv.Volume = 0;
}
}
使用方式
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Test : MonoBehaviour
{
public Button btn_Speak;
public Button btn_StopPlay;
void Start()
{
btn_Speak.onClick.AddListener(delegate
{
SpeechManager.Instance.Speak("你好");
});
btn_StopPlay.onClick.AddListener(delegate
{
SpeechManager.Instance.StopSpeak();
});
}
}
链接:https://pan.baidu.com/s/1nOBg2fQH3IKURS6x_GTEIA?pwd=cc89
提取码:cc89
–来自百度网盘超级会员V7的分享