SpeechSynthesizer.SelectVoice切换pt-BR语音时异常求助
解决SpeechSynthesizer选择Microsoft Maria Desktop语音失败的问题
我最近碰到了一个棘手的小问题:用SpeechSynthesizer调用英语语音(en-US, Helen)时一切正常,但切换到巴西葡萄牙语的Maria语音时,程序直接抛出了“语音未安装或已禁用”的异常。
为了确认语音是否真的安装,我先运行了这段代码检查已安装的语音列表:
Console.WriteLine("Installed voices -"); foreach (InstalledVoice voice in synth.GetInstalledVoices()) { VoiceInfo info = voice.VoiceInfo; Console.WriteLine(" Voice Name: " + info.Name + info.Culture + info.Description); }
输出结果明确显示Maria语音已经安装:
Voice Name: Microsoft David Desktopen-USMicrosoft David Desktop - English (United States)
Voice Name: Microsoft Zira Desktopen-USMicrosoft Zira Desktop - English (United States)
Voice Name: Microsoft Maria Desktoppt-BRMicrosoft Maria Desktop - Portuguese(Brazil)
而我原本设置语音的代码是这样的:
using (var synth = new SpeechSynthesizer()) { synth.SelectVoice("Microsoft Server Speech Text to Speech Voice (pt-BR, Maria)"); synth.Volume = 100; // (0 - 100) synth.Rate = 0; // (-10 - 10) synth.Speak("Central esta Off-Line"); }
问题根源与解决方案
问题其实出在传入SelectVoice的语音名称不匹配!从已安装语音的输出可以看到,Maria的实际名称是Microsoft Maria Desktop,而不是我之前误用的服务器版语音名称。
修改后的正确代码如下:
using (var synth = new SpeechSynthesizer()) { // 使用实际安装的语音名称 synth.SelectVoice("Microsoft Maria Desktop"); synth.Volume = 100; synth.Rate = 0; synth.Speak("Central esta Off-Line"); }
如果想要更灵活、避免硬编码名称出错的话,还可以通过文化信息(Culture)来筛选语音:
using (var synth = new SpeechSynthesizer()) { var brazilianCulture = new System.Globalization.CultureInfo("pt-BR"); var mariaVoice = synth.GetInstalledVoices(brazilianCulture) .FirstOrDefault(v => v.VoiceInfo.Name.Contains("Maria")); if (mariaVoice != null) { synth.SelectVoice(mariaVoice.VoiceInfo.Name); synth.Volume = 100; synth.Rate = 0; synth.Speak("Central esta Off-Line"); } else { Console.WriteLine("Maria voice not found!"); } }
我已经确认所有语音包组件都正确安装,修改后程序就能正常运行了,希望这个方案能帮到遇到同样问题的朋友。
内容的提问来源于stack exchange,提问作者Breno Almeida
相关产品推荐
相关产品推荐

