Nitesh Nitesh -4 years ago 107
C# Question

Prevent C# Speech Synthesizer repeating itself on button click event

I have a WPF application that uses the C# Speech Synthesizer. It reads sentences when particular buttons are clicked. An example is below

private void SpeechButton_Click(object sender, RoutedEventArgs e)
{
Speech.SpeakAsync("Hello, Welcome to the application");
Speech.Rate = 2;
}


The problem is if the button is pressed 100 times, the Speech Synthesizer will try and say the sentence 100 times rather than starting the sentence from the top if it has been repeatedly pressed.

Is there any way to avoid this happening?

I have previously tried the below but it didn't work, though there were no errors

base.onclosing


I have also tried changing the rate of speech but no luck

Answer Source

Doco: https://msdn.microsoft.com/en-us/library/system.speech.synthesis.speechsynthesizer(v=vs.110).aspx

EXACTLY THIS: https://msdn.microsoft.com/en-us/library/jj572477(v=office.14).aspx#Anchor_4

Something like the following should work, your just creating a variable that can be accessed so its a single instance of speechsynthesizer

private SpeechSynthesizer synth = new SpeechSynthesizer();
private void SpeechButton_Click(object sender, RoutedEventArgs e)
{
    // Cancel the current speak operation and all queued SpeakAsync operations.
    synth.SpeakAsyncCancelAll();

    // Begin speaking the prompt.
    synth.SpeakAsync("Hello, Welcome to the application");
}

See that second link for more example code, basically just use a variable to track the same instance and a Cancel type method (several examples in first and second link) to stop current running speeches.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download