2

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?

3

1 Answer 1

4

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.)

1
  • BTW -- the mediaElement needs to be in the visual tree. See The Long Walk blog with detail. Dec 26, 2016 at 6:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.