如何等待语音合成完成

How to wait for a speech synthesis to complete

我正在编写一个 WP8.1 应用程序,并尝试通过以下方式输出语音:

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();
}

这确实有效...但它似乎同时播放两者 - 所以它听起来像是回声。我看不出有什么方法可以等待播放结束,或者在播放结束时收到通知 - 有吗?

MediaElement 有一个 MediaEnded 事件。您可以使用 TaskCompletionSource 等待它:

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

await tsc.Task;

(请仔细检查事件是否被触发,即使媒体播放以某种方式被取消。)