简体   繁体   中英

C#: Execute Event immediately when it's raised

I'm currently working on a text-to-speech application in C# with WPF.

To restart the playback, I need to cancel it first and then start it once again.
I have added an function( speaker_finished() ) to the SpeakCompleted EventHandler that get's called when the playback is finished or cancelled. speaker_finished() calls outputVisible(false) that sets some UI elements to invisible. But when I restart the playback I want them to stay visible.
For that outputVisible(true) gets called after speaker.SpeakAsyncCancelAll() . This cancels the playback and then sets the UI elements to visible. The issue is that speaker_finished() gets called after buttonRestart_Click() is finished and thus too late. I want it to get called right after I cancel the playback with speaker.SpeakAsyncCancelAll() and before outputVisible(true) gets called.

How can I achieve that?

SpeechSynthesizer speaker = new SpeechSynthesizer();

private void buttonRestart_Click(object sender, RoutedEventArgs e)
    {
        speaker.SpeakAsyncCancelAll();
        outputVisible(true);         //this function needs to be called after the function in the event handler
        speaker_Start();
    }

//function in the EventHandler of SpeakFinished
private void speaker_Finished(object sender, SpeakCompletedEventArgs e)
    {
        outputVisible(false);
    }

//function that changes the visibility
private void outputVisible(bool b)
    {
        if(b)
        {
            textBlockOutput.Visibility = Visibility.Visible;
            foreach (UIElement UIEle in GridPlaybackButtons.Children)
            {
                UIEle.Visibility = Visibility.Visible;
            }
        }
        else
        {
            textBlockOutput.Visibility = Visibility.Hidden;
            foreach (UIElement UIEle in GridPlaybackButtons.Children)
            {
                UIEle.Visibility = Visibility.Hidden;
            }
        }
    }

//function that starts the SpeechSynthesizer
private void speaker_Start()
    {
        if (speaker.State == SynthesizerState.Ready)
        {
            speaker.SpeakAsync(speakString);
        }
        else
        {
            MessageBox.Show("There already is a text being output!","Error!", MessageBoxButton.OK);
        }
    }

SpeechSynthesizer has a SpeakStarted event as well. Try adding an event handler for it as you did for SpeakCompleted

private void speaker_Started(object sender, SpeakStartedEventArgs e)
{
    outputVisible(true);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM