/// <summary> /// Fired when we should load the content. /// </summary> /// <param name="source"></param> public void OnPrepareContent() { // Since this can be costly kick it off to a background thread so we don't do work // as we are animating. Task.Run(async() => { // Get the video Uri YouTubeUri youTubeUri = await GetYouTubeVideoUrl(m_base.Source); // Back to the UI thread with pri await global::Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { if (youTubeUri == null) { // If we failed fallback to the browser. m_base.FireOnFallbackToBrowser(); return; } // Setup the video m_youTubeVideo = new MediaElement(); m_youTubeVideo.AutoPlay = false; m_youTubeVideo.AreTransportControlsEnabled = true; m_youTubeVideo.CurrentStateChanged += MediaElement_CurrentStateChanged; m_youTubeVideo.Source = youTubeUri.Uri; ui_contentRoot.Children.Add(m_youTubeVideo); }); }); }
/// <summary> /// Called by the host when we should show content. /// </summary> /// <param name="post"></param> public void OnPrepareContent(Post post) { // So the loading UI m_host.ShowLoading(); // Since this can be costly kick it off to a background thread so we don't do work // as we are animating. Task.Run(async() => { // Get the video Uri YouTubeUri youTubeUri = await GetYouTubeVideoUrl(post); // Back to the UI thread with pri await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { if (youTubeUri == null) { m_host.ShowError(); App.BaconMan.TelemetryMan.ReportUnExpectedEvent(this, "FailedToGetYoutubeVideoAfterSuccess"); return; } // Setup the video m_youTubeVideo = new MediaElement(); m_youTubeVideo.AutoPlay = false; m_youTubeVideo.AreTransportControlsEnabled = true; m_youTubeVideo.CurrentStateChanged += MediaElement_CurrentStateChanged; m_youTubeVideo.Source = youTubeUri.Uri; ui_contentRoot.Children.Add(m_youTubeVideo); }); }); }
private async Task <YouTubeUri> ParsingYouTubeUrl(HtmlNode node) { YouTubeUri uri = new YouTubeUri(); string linkVideo = node.Descendants("iframe").FirstOrDefault().Attributes["src"].Value; return(await GetYouTubeYriForControl(linkVideo)); }
private async Task LoadFilmDetails() { this.gFilmInfo.Visibility = Windows.UI.Xaml.Visibility.Visible; ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile(); ConnectionCost InternetConnectionCost = (InternetConnectionProfile == null ? null : InternetConnectionProfile.GetConnectionCost()); Task <YouTubeUri> tYouTube = null; if (!String.IsNullOrEmpty(SelectedFilm.YoutubeTrailer) && InternetConnectionProfile != null && InternetConnectionProfile.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess && InternetConnectionCost != null && InternetConnectionCost.NetworkCostType == NetworkCostType.Unrestricted) { tYouTube = MyToolkit.Multimedia.YouTube.GetVideoUriAsync(SelectedFilm.YoutubeTrailer, Config.TrailerQuality); } if (tYouTube != null) { try { this.trailerUrl = await tYouTube; } catch { } } this.spFilmButtons.Visibility = this.btnTrailer.Visibility = btnPlay.Visibility = (trailerUrl != null ? Windows.UI.Xaml.Visibility.Visible : Windows.UI.Xaml.Visibility.Collapsed); this.mpTrailer.Visibility = Windows.UI.Xaml.Visibility.Collapsed; }
protected async override void OnNavigatedTo(NavigationEventArgs e) { try { if (NetworkInterface.GetIsNetworkAvailable()) { video = e.Parameter as Video; YouTubeUri url = await MyToolkit.Multimedia.YouTube.GetVideoUriAsync(video.Id, YouTubeQuality.Quality1080P); Player.Source = url.Uri; Player.Play(); } else { MessageDialog message = new MessageDialog("you are not connect to internet"); await message.ShowAsync(); this.Frame.GoBack(); } } catch (Exception exception) { Console.WriteLine(exception.Message); } base.OnNavigatedTo(e); }
private async Task LoadPage() { progressRing.IsActive = true; try { mainVideo = await MyToolkit.Multimedia.YouTube.GetVideoUriAsync(video.Id, selectedQuality); mediaPlayer.Source = mainVideo.Uri; mediaPlayer.Play(); progressRing.IsActive = false; } catch (Exception ex) { if (ex.HResult == -2146233088) { MessageDialog m = new MessageDialog("Quality Not Supported, try something else", "WinBeta Videos Error"); await m.ShowAsync(); } else { MessageDialog m = new MessageDialog("Could play video: " + ex.Message, "WinBeta Videos Error"); await m.ShowAsync(); } progressRing.IsActive = false; } }
protected async override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); RootObject myChannel = await YoutubeProxy.GetChannel(); txtTitle.Text = myChannel.items[0].snippet.channelTitle; ResultDescription.Text = myChannel.items[0].snippet.description; string YoutubeId = myChannel.items[0].contentDetails.upload.videoId; YouTubeUri url = await YouTube.GetVideoUriAsync(YoutubeId, YouTubeQuality.Quality720P); YoutubePlayer.Source = url.Uri; YoutubePlayer.Play(); }
private async Task LoadFilmDetails() { ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile(); ConnectionCost InternetConnectionCost = (InternetConnectionProfile == null ? null : InternetConnectionProfile.GetConnectionCost()); Task <YouTubeUri> tYouTube = null; if (InternetConnectionProfile != null && InternetConnectionProfile.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess) { if (!String.IsNullOrEmpty(SelectedFilm.YoutubeTrailer) && InternetConnectionCost != null && InternetConnectionCost.NetworkCostType == NetworkCostType.Unrestricted) { tYouTube = MyToolkit.Multimedia.YouTube.GetVideoUriAsync(SelectedFilm.YoutubeTrailer, Config.TrailerQuality); } } this.DataContext = this; CinemaData cd = new CinemaData(App.FilmCinemas[SelectedFilm.EDI]); dataLetter = cd.GroupsByLetter; cvsCinemas.Source = dataLetter; gvZoomedInCinemas.SelectionChanged -= gvZoomedIn_SelectionChanged; gvZoomedInCinemas.SelectedItem = null; (semanticZoom.ZoomedOutView as ListViewBase).ItemsSource = cd.CinemaHeaders; gvZoomedInCinemas.SelectionChanged += gvZoomedIn_SelectionChanged; semanticZoom.ViewChangeStarted -= semanticZoom_ViewChangeStarted; semanticZoom.ViewChangeStarted += semanticZoom_ViewChangeStarted; if (tYouTube != null) { try { this.trailerUrl = await tYouTube; } catch { } } this.btnTrailer.Visibility = btnPlay.Visibility = (trailerUrl != null ? Windows.UI.Xaml.Visibility.Visible : Windows.UI.Xaml.Visibility.Collapsed); this.mpTrailer.Visibility = Windows.UI.Xaml.Visibility.Collapsed; //if(taskFilmReviews != null) // await taskFilmReviews; }
async private void youtubePlay(String link) { string[] arr = link.Split("="); var youtubeid = arr[1]; Debug.WriteLine(youtubeid); try { YouTubeUri uri = await YouTube.GetVideoUriAsync(youtubeid, YouTubeQuality.Quality1080P); Debug.WriteLine(uri); mediaPlayer.SetUriSource(uri.Uri); } catch (Exception e) { e.ToString(); } }
protected override async void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); String YouTubeId = "eFajTI4lOHM"; try { YouTubeUri url = await YouTube.GetVideoUriAsync(YouTubeId, YouTubeQuality.Quality360P); reproductor.Source = url.Uri; reproductor.Play(); } catch (Exception) { // TODO show error (video uri not found) } }
private async void button2_Click(object sender, RoutedEventArgs e) { async Task <Uri> GetYoutubeUri(string jItnCGRsMjw) { YouTubeUri uri = await YouTube.GetVideoUriAsync(jItnCGRsMjw, YouTubeQuality.Quality1080P); return(uri.Uri); } Uri _videoUri = await GetYoutubeUri("jItnCGRsMjw"); if (_videoUri != null) { player.Source = _videoUri; player.Play(); } }
protected override async void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); string YouTubeId = "pA1OaRb9Cb0"; try { YouTubeUri url = await YouTube.GetVideoUriAsync(YouTubeId, YouTubeQuality.Quality360P); MediaElt.Source = url.Uri; MediaElt.Play(); } catch (Exception) { // TODO show error (video uri not found) } }
//async private void OnPageVideoLoaded(object sender, RoutedEventArgs e) //{ //string youtubeId = "mnjbHvYhl-w";//"OgbmOjon0Mw"; //string youtubeId = str; //} async protected override void OnNavigatedTo(NavigationEventArgs e) { string str = e.Parameter as string; string youtubeId = str; //pname.Text = str; try { YouTubeUri url = await YouTube.GetVideoUriAsync(youtubeId, YouTubeQuality.Quality360P); //txtblk.Text = "Uri = " + url.Uri.ToString(); mediaElt.Source = url.Uri; mediaElt.AreTransportControlsEnabled = true; mediaElt.MaxHeight = 320; //mediaElt.IsMuted = true; mediaElt.Play(); } catch (Exception) { } base.OnNavigatedTo(e); }
/// <summary> /// Вызывается перед отображением этой страницы во фрейме. /// </summary> /// <param name="e">Данные события, описывающие, каким образом была достигнута эта страница. /// Этот параметр обычно используется для настройки страницы.</param> protected async override void OnNavigatedTo(NavigationEventArgs e) { DisplayInformation.AutoRotationPreferences = DisplayOrientations.Portrait | DisplayOrientations.Landscape | DisplayOrientations.LandscapeFlipped; if (e.Parameter != null) { DisplayInformation.DisplayContentsInvalidated += DisplayInformation_DisplayContentsInvalidated; string[] param = (string[])e.Parameter; HeaderNews.Text = param[0]; DateNews.Text = param[1]; OneNews oneNews = await NewsElementParser.Parse(param[2]); DescrNews.Text = oneNews.Description; YouTubeQuality quality = YouTubeQuality.Quality360P; if (Settings.Settings.QualityYouTubeVideo != null) { switch (Settings.Settings.QualityYouTubeVideo) { case "144p": quality = YouTubeQuality.Quality144P; break; case "240p": quality = YouTubeQuality.Quality240P; break; case "360p": quality = YouTubeQuality.Quality360P; break; case "480p": quality = YouTubeQuality.Quality480P; break; case "720p": quality = YouTubeQuality.Quality720P; break; case "1080p": quality = YouTubeQuality.Quality1080P; break; } } YouTubeUri videoUri = null; bool error = false; try { videoUri = await YouTube.GetVideoUriAsync(oneNews.YouTubeID, quality); } catch (YouTubeUriNotFoundException) { error = true; } if (!error && videoUri != null) { playerYouTube.Source = videoUri.Uri; } else { var dialog = new MessageDialog("Не удалось загрузить видео. \nПопробуйте поменять качество в настройках."); await dialog.ShowAsync(); } } else { if (Frame.CanGoBack) { Frame.GoBack(); } } }
internal async Task <Uri> GetYoutubeUri(string VideoID) { YouTubeUri uri = await YouTube.GetVideoUriAsync(VideoID, YouTubeQuality.NotAvailable); return(uri.Uri); }
private static async void OnHtmlParse(string response, Action<List<YouTubeUri>, Exception> completed) { var urls = new List<YouTubeUri>(); try { var match = Regex.Match(response, "url_encoded_fmt_stream_map\": \"(.*?)\""); var data = Uri.UnescapeDataString(match.Groups[1].Value); var arr = Regex.Split(data, ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"); // split by comma but outside quotes foreach (var d in arr) { var url = ""; var signature = ""; var tuple = new YouTubeUri(); foreach (var p in d.Replace("\\u0026", "\t").Split('\t')) { var index = p.IndexOf('='); if (index != -1 && index < p.Length) { try { var key = p.Substring(0, index); var value = Uri.UnescapeDataString(p.Substring(index + 1)); if (key == "url") url = value; else if (key == "itag") tuple.Itag = int.Parse(value); //else if (key == "type" && value.Contains("video/mp4")) //只获取Mp4 else if (key == "type") //获取全部 tuple.Type = value; else if (key == "s") { signature = await DecryptWebSignature(value); //signature = DecryptLocalSignature(value); } else if (key == "sig") signature = value; } catch { } } } tuple.url = url + "&signature=" + signature; if (tuple.IsValid) urls.Add(tuple); } } catch (Exception ex) { if (completed != null) completed(null, ex); return; } //降序排列 var entry = urls.OrderByDescending(u => u.Itag).ToList(); if (entry != null) { if (completed != null) completed(entry, null); } else if (completed != null) completed(null, new Exception("no_video_urls_found")); }
private static async void OnHtmlParse(string response, DecryptSignatureMode decryptSignatureMode, Action<List<YouTubeUri>, Exception> completed) { var urls = new List<YouTubeUri>(); if (sigCodes != null && sigCodes.Count > 0) sigCodes.Clear(); javaScriptCode = string.Empty; try { //var match = Regex.Match(response, "url_encoded_fmt_stream_map\": \"(.*?)\""); var match = Regex.Match(response, "url_encoded_fmt_stream_map\"\\s*:\\s*\"(.*?)\""); var data = Uri.UnescapeDataString(match.Groups[1].Value); match = Regex.Match(response, "adaptive_fmts\": \"(.*?)\""); var data2 = Uri.UnescapeDataString(match.Groups[1].Value); var arr = Regex.Split(data + "," + data2, ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"); // split by comma but outside quotes foreach (var d in arr) { var url = ""; var signature = ""; var tuple = new YouTubeUri(); foreach (var p in d.Replace("\\u0026", "\t").Split('\t')) { var index = p.IndexOf('='); if (index != -1 && index < p.Length) { try { var key = p.Substring(0, index); var value = Uri.UnescapeDataString(p.Substring(index + 1)); if (key == "url") url = value; else if (key == "itag") tuple.Itag = int.Parse(value); //else if (key == "type" && (value.Contains("video/mp4") || value.Contains("audio/mp4"))) //只获取Mp4 else if (key == "type") //获取全部 tuple.Type = value; else if (key == "s") { if (decryptSignatureMode == DecryptSignatureMode.DecryptLocalSignature) signature = await DecryptLocalSignature(value, response); else signature = await DecryptWebSignature(value); } else if (key == "sig") signature = value; } catch (Exception exception) { Debug.WriteLine("YouTube parse exception: " + exception.Message); } } } if (url.Contains("&signature=") || url.Contains("?signature=")) tuple.url = url; else tuple.url = url + "&signature=" + signature; if (tuple.IsValid) urls.Add(tuple); } } catch (Exception ex) { if (completed != null) completed(null, ex); return; } //降序排列 var entry = urls.OrderByDescending(u => u.Itag).ToList(); if (entry != null) { if (completed != null) completed(entry, null); } else if (completed != null) completed(null, new Exception("no_video_urls_found")); }
private static async void OnHtmlDownloaded(string response, YouTubeQuality minQuality, YouTubeQuality maxQuality, Action<YouTubeUri, Exception> completed) { var urls = new List<YouTubeUri>(); try { var match = Regex.Match(response, "url_encoded_fmt_stream_map\": \"(.*?)\""); var data = Uri.UnescapeDataString(match.Groups[1].Value); var arr = Regex.Split(data, ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"); // split by comma but outside quotes foreach (var d in arr) { var url = ""; var signature = ""; var tuple = new YouTubeUri(); foreach (var p in d.Replace("\\u0026", "\t").Split('\t')) { var index = p.IndexOf('='); if (index != -1 && index < p.Length) { try { var key = p.Substring(0, index); var value = Uri.UnescapeDataString(p.Substring(index + 1)); if (key == "url") url = value; else if (key == "itag") tuple.Itag = int.Parse(value); //else if (key == "type" && value.Contains("video/mp4")) //只获取Mp4 else if (key == "type") //获取全部 tuple.Type = value; else if (key == "s") { signature = await DecryptWebSignature(value); //signature = DecryptLocalSignature(value); } else if (key == "sig") signature = value; } catch { } } } tuple.url = url + "&signature=" + signature; if (tuple.IsValid) urls.Add(tuple); } var minTag = GetQualityIdentifier(minQuality); var maxTag = GetQualityIdentifier(maxQuality); //foreach (var u in urls.Where(u => u.Itag < minTag || u.Itag > maxTag).ToArray()) //得到相对命中的,如果没用命中绝对项,会找到目标项[上一级或下一级(相邻)]的项 foreach (var u in urls.Where(u => u.Itag <= minTag || u.Itag >= maxTag).ToArray()) //得到绝对命中的 urls.Remove(u); } catch (Exception ex) { if (completed != null) completed(null, ex); return; } var entry = urls.OrderByDescending(u => u.Itag).FirstOrDefault(); if (entry != null) { if (completed != null) completed(entry, null); } else if (completed != null) //completed(null, new Exception("no_video_urls_found")); completed(entry, null); }
protected async override void OnNavigatedTo(NavigationEventArgs e) { SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible; SystemNavigationManager.GetForCurrentView().BackRequested += NewsElement_BackRequested; DisplayInformation.AutoRotationPreferences = DisplayOrientations.Portrait | DisplayOrientations.Landscape | DisplayOrientations.LandscapeFlipped; //ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile(); //NetworkConnectivityLevel connection = InternetConnectionProfile.GetNetworkConnectivityLevel(); //bool internetAccess = !(connection == NetworkConnectivityLevel.None || connection == NetworkConnectivityLevel.LocalAccess); bool internetAccess = NetworkInterface.GetIsNetworkAvailable(); if (internetAccess && e.Parameter != null) { DisplayInformation.GetForCurrentView().OrientationChanged += NewsElement_OrientationChanged; string[] param = (string[])e.Parameter; HeaderNews.Text = param[0]; DateNews.Text = param[1]; OneNewsModel oneNews = await NewsElementParser.Parse(param[2]); DescrNews.Text = oneNews.Description; YouTubeQuality quality = YouTubeQuality.Quality360P; if (Settings.Settings.QualityYouTubeVideo != null) { switch (Settings.Settings.QualityYouTubeVideo) { case "360p": quality = YouTubeQuality.Quality360P; break; case "480p": quality = YouTubeQuality.Quality480P; break; case "720p": quality = YouTubeQuality.Quality720P; break; case "1080p": quality = YouTubeQuality.Quality1080P; break; } } YouTubeUri videoUri = null; bool error = false; try { videoUri = await YouTube.GetVideoUriAsync(oneNews.YouTubeID, quality); } catch (YouTubeUriNotFoundException) { error = true; } if (!error && videoUri != null) { playerYouTube.MediaPlayer.SetUriSource(videoUri.Uri); } else { var dialog = new MessageDialog("Не удалось загрузить видео."); await dialog.ShowAsync(); Frame.GoBack(); } } else { var dialog = new MessageDialog("Проверьте соединение с интернетом"); await dialog.ShowAsync(); Frame.GoBack(); } }