Xamarin.forms 新媒体元素不播放 youtube 视频

Xamarin.forms new Media element not playing youtube video

我正在实施 xamarin 表单媒体元素。我能够播放 xamarin 媒体元素官方文档中提供的 link 中的视频。但问题是我想播放 youtube 视频,但它没有播放。我已经在 app.xaml.cs 中设置了标志,但 youtube 视频仍然没有任何反应。它只在模拟器和物理设备中显示黑屏。

<MediaElement Source="https://youtu.be/E7Voso411Vs" x:Name="mediaSource"
                          AutoPlay="True" ShowsPlaybackControls="True" 
                          VerticalOptions="FillAndExpand" />

希望得到解决。
谢谢。

您应该首先使用 https://www.youtube.com/get_video_info?video_id={VideoId} 从 youtube 中提取 url,试试这个:

<MediaElement  x:Name="mediaSource"
             AutoPlay="True" ShowsPlaybackControls="True" 
             VerticalOptions="FillAndExpand" />

然后在你的 page.cs:

public MediaElem()
    {
        InitializeComponent();

        mediaSource.Source = GetYouTubeUrl("E7Voso411Vs");

    }



public string GetYouTubeUrl(string videoId)
    {
        var videoInfoUrl = $"https://www.youtube.com/get_video_info?video_id={videoId}";
        using (var client = new HttpClient())
        {
            var videoPageContent = client.GetStringAsync(videoInfoUrl).Result;
            var videoParameters = HttpUtility.ParseQueryString(videoPageContent);
            var encodedStreamsDelimited1 = WebUtility.HtmlDecode(videoParameters["player_response"]);
            JObject jObject = JObject.Parse(encodedStreamsDelimited1);
            string url = (string)jObject["streamingData"]["formats"][0]["url"];
            return url;           
        }
    }

是的,不能直接播放。首先,您必须将该 youtube 视频 url 转换为流媒体,您可以使用 YoutubeExplode plugin.

var videoId = (string)parameters["videoId"];
var videoURL = $"https://www.youtube.com/watch?v={videoId}";
var youtube = new YoutubeClient();

var streamManifest = await youtube.Videos.Streams.GetManifestAsync(videoId);
var streamInfo = streamManifest.GetMuxed().WithHighestVideoQuality();

if (streamInfo != null)
{
    // Get the actual stream
    var stream = await youtube.Videos.Streams.GetAsync(streamInfo);
    var source = streamInfo.Url;

   // Then use it with MediaElement
   mediaSource.Source = source; 
}