.NET SpeechSynthesizer 抛出 System.NullReferenceException

问题描述

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

我正在尝试在我的应用程序中使用 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 相关问题的简单重复。以下是一些可能有助于提供答案的类似问题:

解决方法

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

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