需要提前做以下設置:
-
Unity中需要設置:
Editor -> Project Settings -> Player -> Other Settings -> Api Compatibility Level -> 選擇.Net 4.x -
系統(tǒng)需要提前下載中文語音包
Win11可以在 設置 -> 時間和語言 -> 語音 中查看已下載的語音
其中Huihui Yaoyao Kangkang為中文語音,下面腳本也是這樣判斷的
如果沒有安裝語音的話,可以在設置 -> 時間和語言 -> 語言和區(qū)域 -> 語言選項中查看安裝文章來源:http://www.zghlxwxcb.cn/news/detail-747571.html
腳本
將下面腳本掛載到場景中GameObject上,然后通過其他方法對其進行實例化和調用文章來源地址http://www.zghlxwxcb.cn/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);
}
//開始執(zhí)行 異步朗讀
_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>
/// 語音播放繼續(xù)
/// </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($"繼續(xù)播放失?。?{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模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!