[英]How to combine asynchronous method with synchronous method in C#?
我是從主要方法調用的:
public MainPage()
{
Text_to_Speech.changetospeech("Welcome to Nepal!", newmedia).Wait();
mytxtblck.Text="Hello from Nepal!"
}
我真正想做的是Wait
“歡迎來到尼泊爾”,然后在mytextblck
寫下“Hello”。
我已經去了幾個線程並且工作了,但沒有任何東西可以使它工作。
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();
}
聽起來你真正想要的是在觸發MediaEnded
事件時觸發文本更改。
你可以在你的ChangeToSpeech
方法中做到這一點,雖然它會有點難看:
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.