如何从流创建 IMediaPlaybackSource,以便在不使用过时的 SetStreamSource 方法的情况下设置 MediaPlayer 源?

How do I create an IMediaPlaybackSource from a Stream, so as to set a MediaPlayer source without using the obsolete SetStreamSource method?

我正在尝试开发一个 UWP 应用程序,它将通过 Windows.Media.Playback.MediaPlayer 向用户朗读文本。我有目前有效的代码:

    private async Task Speak(string text)
    {
        var audio = await _Speech.SynthesizeTextToStreamAsync(text);
        player.SetStreamSource(audio);
        player.Play();
    }

但是,这会导致编译器警告:'MediaPlayer.SetStreamSource(IRandomAccessStream)' is obsolete: 'Use Source instead of SetStreamSource. For more info, see MSDN.

但是,我在 MSDN 上找不到如何将 SynthesizeTextToStreamAsync 生成的 SpeechSynthesisStream 转换为 MediaPlayer 想要的 IMediaPlaybackSourceWindows.Media.Core.MediaStreamSource class 看起来很有前途,但它想要一个 IMediaStreamDescriptor,我不知道如何获得...

如何在不使用已弃用方法的情况下复制这个简单的三行代码的功能?

SynthesizeTextToStreamAsync returns 您可以使用的 SpeechSynthesisStream 对象。 MSDN 文档中的这个示例应该会引导您朝着正确的方向前进

   SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync("Hello World");

   mediaElement.SetSource(stream, stream.ContentType); 

https://docs.microsoft.com/en-us/uwp/api/windows.media.speechsynthesis.speechsynthesizer

您可以使用 MediaSource.CreateFromStream() 方法来达到此目的。

private async Task Speak(string text)
{
    var audio = await _Speech.SynthesizeTextToStreamAsync(text);
    player.Source = MediaSource.CreateFromStream(audio);
    player.Play();
}