代码之家  ›  专栏  ›  技术社区  ›  drumjojo

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

  •  1
  • drumjojo  · 技术社区  · 8 年前

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


    我添加了一个函数( speaker_finished() SpeakCompleted 播放完成或取消时调用的EventHandler。 outputVisible(false) 将某些UI元素设置为不可见。但当我重新开始播放时,我希望它们保持可见。
    为了这个 outputVisible(true) 在之后被调用 speaker.SpeakAsyncCancelAll() 问题是 扬声器_完成() 在之后被调用 buttonRestart_Click() 已完成,因此为时已晚。我希望在用取消播放后立即调用它 speaker.SpeakAsyncCancelAll() 和之前 输出可见(真) 被调用。

    我如何才能做到这一点?

    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 回复  |  直到 8 年前
        1
  •  0
  •   dukedukes    8 年前

    SpeechSynthesizer 有一个 SpeakStarted 事件。尝试为其添加事件处理程序 SpeakCompleted

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