Xamarin.forms new Media element not playing youtube video

Viewed 2591

I was implementing xamarin forms Media element. I'm able to play videos from the link provided in xamarin media element official doc. but the problem is i want to play youtube video but it isn't playing. I have set the flag in app.xaml.cs but still nothing happened for youtube videos. It only shows blank screen in both emulator and in physical device.

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

Hope to get solution.
Thank you.

2 Answers

You should extract url from youtube with https://www.youtube.com/get_video_info?video_id={VideoId} first,try this:

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

then in your 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;           
        }
    }

Yes, you can not play it directly. First you have to convert that youtube video url into stream, you can do that using 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; 
}
Related