需要提前做以下设置:
-
Unity中需要设置:
Editor -> Project Settings -> Player -> Other Settings -> Api Compatibility Level -> 选择.Net 4.x -
系统需要提前下载中文语音包
Win11可以在 设置 -> 时间和语言 -> 语音 中查看已下载的语音
其中Huihui Yaoyao Kangkang为中文语音,下面脚本也是这样判断的
如果没有安装语音的话,可以在设置 -> 时间和语言 -> 语言和区域 -> 语言选项中查看安装
文章来源:https://www.toymoban.com/news/detail-747571.html
脚本
将下面脚本挂载到场景中GameObject上,然后通过其他方法对其进行实例化和调用文章来源地址https://www.toymoban.com/news/detail-747571.html
using UnityEngine;
using SpeechLib;
using System;
namespace Project
{
/// <summary>
/// 微软文字转语音
/// </summary>
public class SpeechLibText_ZH : MonoBehaviour
{
//微软组件
SpVoice _SpVoice;
/// <summary>
/// 语音播放
/// </summary>
/// <param name="_SpeakText"></param>
public void SpeakText(string _SpeakText)
{
try
{
_SpVoice = new SpVoice();
//音量0-100
_SpVoice.Volume = 100;
//语速-10 - 10
_SpVoice.Rate = 0;
//设置中文语音包
ISpeechObjectTokens voices = _SpVoice.GetVoices(string.Empty, string.Empty);
ISpeechObjectToken chineseVoice = null;
ISpeechObjectToken voiceToken = null;
for (int i = 0; i < voices.Count; i++)
{
voiceToken = voices.Item(i);
if (voiceToken.GetDescription().Contains("Huihui") || voiceToken.GetDescription().Contains("Yaoyao") || voiceToken.GetDescription().Contains("Kangkang"))
{
chineseVoice = voiceToken;
Debug.Log("语音:" + voiceToken.GetDescription());
break;
}
}
if (chineseVoice != null)
{
_SpVoice.Voice = chineseVoice as SpObjectToken;
}
else
{
Debug.Log("未检索到语音包,使用默认语音");
_SpVoice.Voice = _SpVoice.GetVoices(string.Empty, string.Empty).Item(0);
}
//开始执行 异步朗读
_SpVoice.Speak(_SpeakText, SpeechVoiceSpeakFlags.SVSFlagsAsync);
}
catch (Exception e)
{
Debug.Log($"播放失败原因:" + e.Message);
}
}
/// <summary>
/// 语音播放暂停
/// </summary>
public void Pause()
{
try
{
_SpVoice.Pause();
}
catch (Exception e)
{
Debug.Log($"暂停失败 原因: {e.Message}");
}
}
/// <summary>
/// 语音播放继续
/// </summary>
public void Resume()
{
try
{
_SpVoice.Volume = (int)(GameEntry.Setting.GetFloat("SFXVolume") * 100);
if (GameEntry.Setting.GetBool("SFXMuted"))
{
_SpVoice.Volume = 0;
}
_SpVoice.Resume();
}
catch (Exception e)
{
Debug.Log($"继续播放失败: {e.Message}");
}
}
/// <summary>
/// 语音播放停止
/// </summary>
public void StopPlaying()
{
try
{
_SpVoice.Speak(string.Empty, SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak);//停止
}
catch (Exception e)
{
Debug.Log($"停止失败: {e.Message}");
}
}
}
}
到了这里,关于Unity 文字转语音 Microsoft Interop.SpeechLib使用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!