我正在实现xamarin形式的Media元素。我可以通过xamarin Media element官方文档中提供的链接播放视频。但问题是我想播放youtube视频,但没有播放。我在app.xaml.cs中设置了标志,但youtube视频仍然没有任何反应。它只会在仿真器和物理设备中显示空白屏幕。
<MediaElement Source="https://youtu.be/E7Voso411Vs" x:Name="mediaSource"
AutoPlay="True" ShowsPlaybackControls="True"
VerticalOptions="FillAndExpand" />
希望得到解决方案。
谢谢。
答案 0 :(得分:3)
您应首先使用https://www.youtube.com/get_video_info?video_id={VideoId}
从youtube提取网址,请尝试以下操作:
<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;
}
}
答案 1 :(得分:1)
是的,您不能直接播放。首先,您必须将youtube视频网址转换为流,您可以使用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;
}