title: .NET SpeechSynthesizer throws System.NullReferenceException
body: <p>I can't seem to find any solutions to my problem anywhere.</p>
  <p>I am trying to use SpeechSynthesizer in my application but anything that I try (including code from the Microsoft documentation) but nothing seems to work. The code that I am using is:</p>
  <pre><code>using (SpeechSynthesizer synth = new SpeechSynthesizer())
  {
      // Configure the audio output.   
      synth.SetOutputToDefaultAudioDevice();
  
      // Speak a string synchronously.  
      synth.Speak(&quot;test&quot;);
  }
  </code></pre>
  <p>I am using the following namespaces</p>
  <pre class="lang-cs prettyprint-override"><code>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;
  </code></pre>
  <p>I got the code from the Microsoft .NET documentation here:
  <a href="https://docs.microsoft.com/en-us/dotnet/api/system.speech.synthesis.speechsynthesizer.speak?view=netframework-4.8" rel="nofollow noreferrer">LINK</a></p>
  <p>The code throws a System.NullReferenceException at <code>synth.SetOutputToDefaultAudioDevice();</code> and when I comment the line out it throws it here too <code>synth.Speak(&quot;test&quot;);</code></p>
  <p>The stack trace says that it is from the System.Speech dll or at least I think it is anyway; I'm not sure. A link to the stack trace is:</p>
  <pre><code>   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
  </code></pre>
  <p>There appear to be other questions that are related to this, and so my question does not appear to be a simple duplicate of other NRE related questions. Here are some similar questions that may help provide an answer:</p>
  <ul>
  <li><a href="https://stackoverflow.com/questions/29253112/nullreference-in-microsoft-speech-when-getting-installed-recognizers-even-though">Nullreference in microsoft.speech</a>...</li>
  <li><a href="https://stackoverflow.com/questions/61149644/nullreferenceexception-with-speechsynthesizer-in-unity">NullReferenceException with SpeechSynthesizer in Unity</a></li>
  </ul>