.NET SpeechSynthesizer throws System.NullReferenceException

935 Views Asked by At

I can't seem to find any solutions to my problem anywhere.

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:

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

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

I am using the following namespaces

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;

I got the code from the Microsoft .NET documentation here: LINK

The code throws a System.NullReferenceException at synth.SetOutputToDefaultAudioDevice(); and when I comment the line out it throws it here too synth.Speak("test");

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:

   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

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:

1

There are 1 best solutions below

0
On BEST ANSWER

It took a while but I found an answer. I didn't have System.Speech installed in the Manage NuGet Packages section. I just added the DLL from Add a project reference but it was not installed so it was throwing the NullReferenceException. For anyone else who has this problem you must install the NuGet package by going to Project > Manage NuGet Packages > Browse then search System.Speech in the search bar, click on the package with the .NET icon and press Install.

Also thanks for everyone who tried to help :)