简体   繁体   中英

How to combine asynchronous method with synchronous method in C#?

I'm calling from the main method:

public MainPage()
{
  Text_to_Speech.changetospeech("Welcome to Nepal!", newmedia).Wait();
  mytxtblck.Text="Hello from Nepal!"
}

What I really want to do is Wait until "Welcome to Nepal" is being spoken and then write "Hello" in mytextblck .

I've gone to several threads and worked, but nothing could make it work.

public async static Task changetospeech(string text, MediaElement mediaa)
{
   var synth = new SpeechSynthesizer();
   var voices = SpeechSynthesizer.AllVoices;

   synth.Voice = voices.First(x => x.Gender == VoiceGender.Female );
   SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(text);

   MediaElement media = mediaa;
   media.SetSource(stream,stream.ContentType);
   media.Play();   
}

It sounds like what you really want is to trigger the text change when the MediaEnded event is fired.

You could do that within your ChangeToSpeech method, although it'll be a little ugly:

public async static Task ChangeToSpeech(string text, MediaElement media)
{
    var synth = new SpeechSynthesizer();
    var voices = SpeechSynthesizer.AllVoices;

    synth.Voice = voices.First(x => x.Gender == VoiceGender.Female);

    SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(text);

    var tcs = new TaskCompletionSource<int>();
    RoutedEventHandler handler = delegate { tcs.TrySetResult(10); };
    media.MediaEnded += handler;
    try
    {
        media.SetSource(stream, stream.ContentType);
        media.Play();
        // Asynchronously wait for the event to fire
        await tcs.Task;
    }
    finally
    {
        media.MediaEnded -= handler;
    }
}

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