异步等待直到TTS完成

时间:2017-03-26 18:15:44

标签: c# asynchronous async-await text-to-speech

我试图:

  1. 用TTS说些什么
  2. 异步等待,直到文本完成
  3. 等待一段时间
  4. 回到起点
  5. 我已经设法做到这一点,但感觉就像一个解决方法,因为我被迫将代码放入synthesizer_SpeakCompleted方法。到目前为止,我的代码如下。我希望有正确方法的任何信息。

    public void TestDelay()
    {
        DoSomeSpeechAndSignalWhenItsDone();
    }
    
    public void DoSomeSpeechAndSignalWhenItsDone()
    {
        form.AccessTxtQnReport += "This is written before the speech" + Environment.NewLine;
        synthesizer.SpeakCompleted += new EventHandler<SpeakCompletedEventArgs>(synthesizer_SpeakCompleted);
        synthesizer.SpeakAsync("this is a load of speech and it goes on quite a while");
    }
    
    async void  synthesizer_SpeakCompleted(object sender, SpeakCompletedEventArgs e)
    {
        //we get here when speech has finished
        form.AccessTxtQnReport += "This is written after the speech" + Environment.NewLine;
        synthesizer.SpeakCompleted -= new EventHandler<SpeakCompletedEventArgs>(synthesizer_SpeakCompleted);
    
        // Do a delay
        await Task.Delay(3000);
        form.AccessTxtQnReport += "This is written after the delay" + Environment.NewLine;
        // this makes it cycle round for ever
        TestDelay();
    }
    

    编辑&gt;谢谢你的回复。我现在已经将代码更改为这似乎有效,并且看起来更好一些:

    // attempt delay using TaskCompletionSource
    private TaskCompletionSource<bool> tcs;
    public void TestDelay()
    {
        tcs = new TaskCompletionSource<bool>();
        DoSomeSpeechAndSignalWhenItsDone();
    }
    
    private async void DoSomeSpeechAndSignalWhenItsDone()
    {          
        form.AccessTxtQnReport += "This is written before the speech" + Environment.NewLine;
        synthesizer.SpeakCompleted += new EventHandler<SpeakCompletedEventArgs>(synthesizer_SpeakCompleted);
        synthesizer.SpeakAsync("this is a load of speech and it goes on quite a while");
        await tcs.Task;
    
        form.AccessTxtQnReport += "This is written after the speech" + Environment.NewLine;
        await Task.Delay(2000);
        form.AccessTxtQnReport += "This is written after the delay" + Environment.NewLine;
    
        // repeat the process ad nauseam
        TestDelay();
    }
    
    private  void synthesizer_SpeakCompleted(object sender, SpeakCompletedEventArgs e)
    {
        //we get here when speech has finished         
        synthesizer.SpeakCompleted -= new EventHandler<SpeakCompletedEventArgs>(synthesizer_SpeakCompleted);
        //set the task as completed:
        tcs.SetResult(true);          
    }
    

0 个答案:

没有答案