Search code examples
c#.netwindows-phone-8.1mediaelementvoice

How to wait for a speech synthesis to complete


I'm writing a WP8.1 app, and am trying to output a voice in the following way:

using (SpeechSynthesizer synth = new SpeechSynthesizer())
{
    var voiceStream = await synth.SynthesizeTextToStreamAsync("test 1");
    MediaElement mediaElement = new MediaElement();
    mediaElement.SetSource(voiceStream, voiceStream.ContentType);
    mediaElement.AutoPlay = false;
    mediaElement.Volume = 1;
    mediaElement.IsMuted = false;                                
    mediaElement.Play();
}
using (SpeechSynthesizer synth = new SpeechSynthesizer())
{
    var voiceStream = await synth.SynthesizeTextToStreamAsync("test 2");
    MediaElement mediaElement = new MediaElement();
    mediaElement.SetSource(voiceStream, voiceStream.ContentType);
    mediaElement.AutoPlay = false;
    mediaElement.Volume = 1;
    mediaElement.IsMuted = false;                                
    mediaElement.Play();
}

And this does work... but it appears to be playing both at the same time - so it just sounds like an echo. I can't see any way to wait the play to finish, or to be notified when it does - is there one?


Solution

  • The MediaElement has a MediaEnded event. You can use TaskCompletionSource to await it:

    var tsc = new TaskCompletionSource<bool>();
    mediaElement.MediaEnded += (o, e) => { tsc.TrySetResult(true); }
    mediaElement.Play();
    
    await tsc.Task;
    

    (Please double check if the event get's fired even if the media playback is canceled somehow.)