C#:当它被引发时立即执行事件

时间:2016-09-24 13:34:58

标签: c# wpf events text-to-speech

我目前正在使用WPF在C#中开发文本到语音转换应用程序。

要重新开始播放,我需要先取消播放然后重新开始播放  我已经向speaker_finished() EventHandler添加了一个函数(SpeakCompleted),该函数在播放完成或取消时被调用。 speaker_finished()调用outputVisible(false)将一些UI元素设置为不可见。但是当我重新开始播放时,我希望它们保持可见 因为在outputVisible(true)之后调用speaker.SpeakAsyncCancelAll()。这会取消播放,然后将UI元素设置为可见。 问题是在speaker_finished()完成后调用buttonRestart_Click()因此为时已晚。我希望在我使用speaker.SpeakAsyncCancelAll()取消播放并且在outputVisible(true)被调用之前立即调用它。

我怎样才能做到这一点?

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);
        }
    }

1 个答案:

答案 0 :(得分:0)

SpeechSynthesizer也有SpeakStarted个事件。尝试为SpeakCompleted

添加事件处理程序
private void speaker_Started(object sender, SpeakStartedEventArgs e)
{
    outputVisible(true);
}