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號