I'm trying to:
- Say something with TTS
- Wait asynchronously until the text has finished
- Wait asynchronously a while
- Return to the start
I have managed to do this, but it feels like a work-around as I am forced to put code in the synthesizer_SpeakCompleted
method. My code so far is below. I would appreciate any info on the right way to do this.
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();
}
EDIT > Thanks for the responses. I have now changed the code to this which seems to work, and looks a bit nicer:
// 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);
}