C# TTS语音播放问题
问题背景:某天在客户电脑上遇到崩溃问题,崩溃日志如下:
System.Runtime.InteropServices.COMException (0x80040154):
检索 COM 类工厂中 CLSID 为 {D9F6EE60-58C9-458B-88E1-2F908FD7F87C} 的组件失败,
原因是出现以下错误: 80040154 没有注册类 (异常来自 HRESULT:0x80040154 (REGDB_E_CLASSNOTREG))。
在 System.Speech.Internal.ObjectTokens.RegistryDataKey..ctor(String fullPath, IntPtr regHandle)
在 System.Speech.Internal.ObjectTokens.RegistryDataKey.Open(String registryPath, Boolean fCreateIfNotExist)
在 System.Speech.Internal.ObjectTokens.SAPICategories.DefaultDeviceOut() 在 System.Speech.Internal.Synthesis.VoiceSynthesis..ctor(WeakReference speechSynthesizer)
在 System.Speech.Synthesis.SpeechSynthesizer.get_VoiceSynthesizer() 在 System.Speech.Synthesis.SpeechSynthesizer.set_Rate(Int32 value)
这个错误表明系统在尝试访问或使用 TTS(文本转语音)功能时,未能找到或注册所需的 COM 组件(CLSID: {D9F6EE60-58C9-458B-88E1-2F908FD7F87C})。
如何复现:
因为我的电脑可以正常播放,所以我百度了一下,得知TTS能力在 磁盘路径 C:\Windows\Speech下,故我将 C:\Windows\Speech目录重命名,便复现了上面的报错。
如何解决:
增加异常捕获,提示TTS组件不可用
using System.Runtime.InteropServices;
using System.Speech.Synthesis;
if (Type.GetTypeFromProgID("SAPI.SpVoice") == null)
{
Console.WriteLine("TTS 不可用,跳过语音功能");
}
else
{
try
{
var synthesizer = new SpeechSynthesizer();
// synthesizer.Rate = 1; // 模拟异常触发 COMException
}
catch (COMException ex) when (ex.ErrorCode == unchecked((int)0x80040154))
{
// 针对特定错误码(0x80040154)的处理
Console.WriteLine($"TTS 组件未注册: {ex.Message}");
// 例如:回退到其他 TTS 引擎或提示用户安装组件
}
catch (COMException ex)
{
// 捕获其他 COM 错误
Console.WriteLine($"COM 错误: {ex.ErrorCode:X8}");
}
catch (Exception ex)
{
// 兜底异常处理
Console.WriteLine($"其他错误: {ex.Message}");
}
}
在安装包中携带 语音包,静默安装语音包(未尝试)
Process.Start("SpeechPlatformRuntime.msi", "/quiet");
Process.Start("MSSpeech_TTS_zh-CN_HuiHui.msi", "/quiet");
获得用户许可后 帮用户安装语音包(未尝试)
运行时:Speech Platform Runtime windows11
Speech Platform Runtime windows10
语音包:安装所需语言的语音包
中文语音包示例:MSSpeech_TTS_zh-CN_HuiHui.msi windows11
MSSpeech_TTS_zh-CN_HuiHui.msi windows10

浙公网安备 33010602011771号