【问题标题】:.NET SpeechSynthesizer throws System.NullReferenceException.NET SpeechSynthesizer 抛出 System.NullReferenceException
【发布时间】:2021-05-26 18:48:55
【问题描述】:

我似乎无法在任何地方找到解决问题的方法。

我正在尝试在我的应用程序中使用 SpeechSynthesizer,但我尝试的任何方法(包括 Microsoft 文档中的代码)但似乎没有任何效果。我使用的代码是:

using (SpeechSynthesizer synth = new SpeechSynthesizer())
{
    // Configure the audio output.   
    synth.SetOutputToDefaultAudioDevice();

    // Speak a string synchronously.  
    synth.Speak("test");
}

我正在使用以下命名空间

using System;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Threading;
using Process = System.Diagnostics.Process;
using System.Speech.Recognition;
using System.Media;
using System.IO;
using System.Speech.Synthesis;

我从此处的 Microsoft .NET 文档中获得了代码: LINK

代码在synth.SetOutputToDefaultAudioDevice(); 处抛出 System.NullReferenceException,当我注释掉该行时,它也会在此处抛出 synth.Speak("test");

堆栈跟踪表明它来自 System.Speech dll,或者至少我认为它是无论如何;我不知道。堆栈跟踪的链接是:

   at System.Speech.Internal.ObjectTokens.RegistryDataKey.HKEYfromRegKey(RegistryKey regKey)
   at System.Speech.Internal.ObjectTokens.RegistryDataKey.RootHKEYFromRegPath(String rootPath)
   at System.Speech.Internal.ObjectTokens.RegistryDataKey.Open(String registryPath, Boolean fCreateIfNotExist)
   at System.Speech.Internal.ObjectTokens.ObjectTokenCategory.Create(String sCategoryId)
   at System.Speech.Internal.ObjectTokens.SAPICategories.DefaultDeviceOut()
   at System.Speech.Internal.Synthesis.VoiceSynthesis..ctor(WeakReference speechSynthesizer)
   at System.Speech.Synthesis.SpeechSynthesizer.get_VoiceSynthesizer()
   at System.Speech.Synthesis.SpeechSynthesizer.get_Voice()
   at SampleSynthesis.Program.Main(String[] args) in C:\Users\Sonic\Desktop\test\Program.cs:line 26

似乎还有其他与此相关的问题,因此我的问题似乎不是其他 NRE 相关问题的简单重复。以下是一些可能有助于提供答案的类似问题:

【问题讨论】:

  • 点击 StackTrace 的放大镜,然后发布文本。您可能没有设置某些内容,这会导致 synth 上的方法出现异常。
  • 对不起,我完全忘了提供堆栈跟踪。它可能有助于解决问题。我已经用堆栈跟踪编辑了这个问题。但是,它确实帮助我了解了我所面临的问题,但我仍然没有找到解决方案。 (供 Dour High Arch 评论)
  • @Kit 我已经使用堆栈跟踪的放大镜版本编辑了帖子。
  • 我不愿意发布答案,但就这个问题而言,您似乎在“好公司”中。搜索 HKEYfromRegKey 会产生几个 NRE 和合成器相关的结果。这可能就像在 Windows 注册表中缺少预期的键一样简单。

标签: .net speechsynthesizer


【解决方案1】:

花了一段时间,但我找到了答案。我没有在“管理 NuGet 包”部分安装 System.Speech。我刚刚从Add a project reference 添加了DLL,但它没有安装,所以它抛出了NullReferenceException。对于遇到此问题的其他人,您必须通过转到 Project > Manage NuGet Packages > Browse 然后在搜索栏中搜索 System.Speech 来安装 NuGet 包,单击带有 .NET 图标的包并按安装。

也感谢所有试图提供帮助的人:)

【讨论】:

    猜你喜欢
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-09
    • 1970-01-01
    • 2022-11-24
    • 2014-11-11
    • 1970-01-01
    相关资源
    最近更新 更多