Search code examples
c#microsoft-speech-platform

Cancel a .Speak with Microsoft.Speech


I'm having an application that uses Microsoft.Speech for TTS. I'm having problems with my TTS, if the stream gets d/c'ed before its done.

public void SpeakTest()
{
  PromptBuilder prompt = new PromptBuilder();
  prompt.AppendText("This is a test prompt...");
  _speechSynthersizer.Speak(prompt);
  prompt.ClearContent();
}

This TTS object can be disposed before the speak is done, which leading to System.IO.EndOfStreamException and System.InvalidOperationException: Cannot change synthesizer's output while speaking. exceptions.

How can I cancel a speak, so when my object is being disposed, it will cancel the speak and dispose the object correctly??


Solution

  • I suggest to use asynchronous version of Speak method i.e. SpeakAsync and try to cancel an asynchronous speak operation, before disposing TTS object, by using one of the following methods: SpeakAsyncCancel or SpeakAsyncCancelAll. Here you can find an example.