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;
}
}
See more on this question at Stackoverflow