MediaPlayerElement.MediaPlayer.PlaybackSession.NaturalDuration 总是 returns 零

MediaPlayerElement.MediaPlayer.PlaybackSession.NaturalDuration always returns zero

我正在开发 TTS(文本到语音)应用程序,我需要显示每个语音的持续时间。问题是它总是 returns 零。欢迎任何帮助。谢谢

    SpeechSynthesizer synthesizer = new SpeechSynthesizer();
    MediaPlayerElement mediaPlayerElement = new MediaPlayerElement();
    SpeechSynthesisStream stream = await synthesizer.SynthesizeTextToStreamAsync("Some text...");
    mediaPlayerElement.Source = MediaSource.CreateFromStream(stream, stream.ContentType);
    mediaPlayerElement.MediaPlayer.Play();
    string strDuration = mediaPlayerElement.MediaPlayer.PlaybackSession.NaturalDuration.Milliseconds.ToString();
    MessageDialog msgDlg = new MessageDialog(strDuration);
    await msgDlg.ShowAsync();

MediaPlayerElement.MediaPlayer.PlaybackSession.NaturalDuration always returns zero

我看到了,看来我们无法MediaPlayer.PlaybackSession.NaturalDuration.Milliseconds获取方法。我会报告,目前我们有一个解决方法来获取 NaturalDuration in NaturalDurationChanged 事件。

private async void Button_Click(object sender, RoutedEventArgs e)
{
    SpeechSynthesizer synthesizer = new SpeechSynthesizer();
    MediaPlayerElement mediaPlayerElement = new MediaPlayerElement();
    SpeechSynthesisStream stream = await synthesizer.SynthesizeTextToStreamAsync("say hello ");
    mediaPlayerElement.Source = MediaSource.CreateFromStream(stream, stream.ContentType);
    mediaPlayerElement.MediaPlayer.Play();
    mediaPlayerElement.MediaPlayer.PlaybackSession.NaturalDurationChanged += PlaybackSession_NaturalDurationChanged; ;

}

private async void PlaybackSession_NaturalDurationChanged(Windows.Media.Playback.MediaPlaybackSession sender, object args)
{
    var duration = sender.NaturalDuration;
    MessageDialog msgDlg = new MessageDialog(duration.TotalSeconds.ToString()+"s");
    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
     {
         await msgDlg.ShowAsync();

     });

}