Unity 文字转语音 Microsoft Interop.SpeechLib使用

需要提前做以下设置:

  1. Unity中需要设置:
    Editor -> Project Settings -> Player -> Other Settings -> Api Compatibility Level -> 选择.Net 4.x

  2. 系统需要提前下载中文语音包
    Win11可以在 设置 -> 时间和语言 -> 语音 中查看已下载的语音

    其中Huihui Yaoyao Kangkang为中文语音,下面脚本也是这样判断的

    如果没有安装语音的话,可以在设置 -> 时间和语言 -> 语言和区域 -> 语言选项中查看安装

脚本

将下面脚本挂载到场景中GameObject上,然后通过其他方法对其进行实例化和调用

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}");
			}
		}
	}
}
posted @ 2023-11-30 16:09  马林林林  阅读(237)  评论(2编辑  收藏  举报