public static HttpResponse Play(string youTubeId, YouTubeQuality maxQuality = YouTubeQuality.Quality480P, Action<Exception> completed = null) { return GetVideoUri(youTubeId, maxQuality, (entry, e) => { if (e != null) { if (completed != null) completed(e); } else { if (completed != null) completed(null); if (entry != null) { var launcher = new MediaPlayerLauncher { Controls = MediaPlaybackControls.All, Media = entry.Uri }; launcher.Show(); } } }); }
public static int GetQualityIdentifier(YouTubeQuality quality) { switch (quality) { //mp4 case YouTubeQuality.Quality240P_3GP: return(36); case YouTubeQuality.Quality360P_MP4: return(18); case YouTubeQuality.Quality720P_MP4: return(22); case YouTubeQuality.Quality1080P_MP4: return(37); //flv case YouTubeQuality.Quality480P_FLV_44KHZ: return(35); case YouTubeQuality.Quality360P_FLV_22KHZ: return(34); //flv 格式为mp3 case YouTubeQuality.QualityMP3_FLV_44KHZ: return(6); case YouTubeQuality.QualityMP3_FLV_22KHZ: return(5); } throw new ArgumentException("maxQuality"); }
public static async Task<YouTubeUri> GetVideoUriAsync(string youTubeId, YouTubeQuality maxQuality = YouTubeQuality.Quality360P_MP4) { //HttpClientHandler handler = new HttpClientHandler(); //handler.UseDefaultCredentials = true; //handler.AllowAutoRedirect = true; //handler.CookieContainer = new CookieContainer(); //using (var client = new HttpClient(handler)) using (var client = new HttpClient()) { //client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"); //client.DefaultRequestHeaders.Add("Accept", "text/html"); client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"); var response = await client.GetAsync("https://www.youtube.com/watch?v=" + youTubeId + "&nomobile=1"); var task = new TaskCompletionSource<YouTubeUri>(); OnHtmlDownloaded(await response.Content.ReadAsStringAsync(), YouTubeQuality.QualityMP3_FLV_22KHZ, maxQuality, (u, e) => { if (u != null) task.SetResult(u); else if (e == null) task.SetResult(u); //task.SetCanceled(); else task.SetException(e); }); return await task.Task; } }
private static YouTubeUri TryFindBestVideoUri(IEnumerable <YouTubeUri> uris, YouTubeQuality minQuality, YouTubeQuality maxQuality) { return(uris .Where(u => u.HasVideo && u.HasAudio && !u.Is3DVideo && u.VideoQuality >= minQuality && u.VideoQuality <= maxQuality) .OrderByDescending(u => u.VideoQuality) .FirstOrDefault()); }
/// <summary> /// This method disables the current page and shows a progress indicator until the youtube movie url has been loaded and starts /// </summary> /// <param name="youTubeId"></param> /// <param name="manualActivatePage">if true add YouTube.CancelPlay() in OnNavigatedTo() of the page (better)</param> /// <param name="maxQuality"></param> /// <param name="completed"></param> public static void Play(string youTubeId, bool manualActivatePage, YouTubeQuality maxQuality = YouTubeQuality.Quality480P, Action<Exception> completed = null) { lock (typeof(YouTube)) { if (oldState != null) return; if (SystemTray.ProgressIndicator == null) SystemTray.ProgressIndicator = new ProgressIndicator(); SystemTray.ProgressIndicator.IsVisible = true; SystemTray.ProgressIndicator.IsIndeterminate = true; var page = PhonePage.CurrentPage; oldState = PageDeactivator.Inactivate(); httpResponse = Play(youTubeId, YouTubeQuality.Quality480P, ex => Deployment.Current.Dispatcher.BeginInvoke( delegate { if (page == PhonePage.CurrentPage) // !user navigated away { if (ex == null) CancelPlay(manualActivatePage); else CancelPlay(false); } if (completed != null) completed(ex); })); } }
private async void MenuFlyoutItem_Click(object sender, RoutedEventArgs e) { var s = sender as MenuFlyoutItem; switch (s.Text) { case "144p": selectedQuality = YouTubeQuality.Quality144P; break; case "240p": selectedQuality = YouTubeQuality.Quality240P; break; case "270p": selectedQuality = YouTubeQuality.Quality270P; break; case "360p": selectedQuality = YouTubeQuality.Quality360P; break; case "480p": selectedQuality = YouTubeQuality.Quality480P; break; case "520p": selectedQuality = YouTubeQuality.Quality520P; break; case "720p": selectedQuality = YouTubeQuality.Quality720P; break; case "1080p": selectedQuality = YouTubeQuality.Quality1080P; break; case "4k": selectedQuality = YouTubeQuality.Quality2160P; break; default: MessageDialog m = new MessageDialog("Ubnknown Quality", "WinBeta Videos Error"); await m.ShowAsync(); break; } try { await LoadPage(); } catch (AggregateException ex) { MessageDialog m = new MessageDialog("Could play video: " + ex.Message, "WinBeta Videos Error"); await m.ShowAsync(); } }
/// <summary>Returns the best matching YouTube stream URI which has an audio and video channel and is not 3D. </summary> /// <returns>The best matching <see cref="YouTubeUri"/> of the video. </returns> /// <exception cref="YouTubeUriNotFoundException">The <see cref="YouTubeUri"/> could not be found. </exception> /// <exception cref="WebException">An error occurred while downloading the resource. </exception> public static async Task<YouTubeUri> GetVideoUriAsync(string youTubeId, YouTubeQuality minQuality, YouTubeQuality maxQuality, CancellationToken token) { var uris = await GetUrisAsync(youTubeId, token); var uri = TryFindBestVideoUri(uris, minQuality, maxQuality); if (uri == null) throw new YouTubeUriNotFoundException(); return uri; }
private static int GetQualityIdentifier(YouTubeQuality quality) { switch (quality) { case YouTubeQuality.Quality480P: return 18; case YouTubeQuality.Quality720P: return 22; case YouTubeQuality.Quality1080P: return 37; } throw new ArgumentException("maxQuality"); }
public void Update(string region, string quality) { _region = region; _quality = _qualityHelper.GetQualityEnum(quality); _categories.Clear(); _guideCategories.Clear(); _channels.Clear(); _settingsNotifier.Notify(new UpdateSettingsEventArgs()); }
public DataSource(IRemoteDataSource remoteDataSource, string region, int maxPageResult, string quality) { _remoteDataSource = remoteDataSource; _categories = new List <IVideoCategory>(); _guideCategories = new List <IGuideCategory>(); _channels = new List <IChannel>(); _region = region.ToUpper(); _maxPageResult = maxPageResult; _qualityHelper = new VideoQuality(); _quality = _qualityHelper.GetQualityEnum(quality); }
/// <summary>Returns the best matching YouTube stream URI which has an audio and video channel and is not 3D. </summary> /// <returns>The best matching <see cref="YouTubeUri"/> of the video. </returns> /// <exception cref="YouTubeUriNotFoundException">The <see cref="YouTubeUri"/> could not be found. </exception> /// <exception cref="WebException">An error occurred while downloading the resource. </exception> public static async Task <YouTubeUri> GetVideoUriAsync(string youTubeId, YouTubeQuality minQuality, YouTubeQuality maxQuality, CancellationToken token) { var uris = await GetUrisAsync(youTubeId, token); var uri = TryFindBestVideoUri(uris, minQuality, maxQuality); if (uri == null) { throw new YouTubeUriNotFoundException(); } return(uri); }
public async Task <YouTubeUri> GetVideoUriAsync(string videoId, YouTubeQuality quality) { //var video = await LiteTube.Multimedia.YouTube.GetVideoUriAsync(videoId, quality);//VideoQualityHelper.GetVideoQuality(quality)); //return video; var video = await YouTube.GetVideoAsync(videoId, VideoQualityHelper.GetVideoQuality(quality), _youTubeServiceControl.OAuthToken); var url = await video.GetUriAsync(); return(new YouTubeUri() { Uri = new Uri(url) }); }
public static HttpResponse GetVideoUri(string youTubeId, YouTubeQuality minQuality, YouTubeQuality maxQuality, Action<YouTubeUri, Exception> completed) { var request = new HttpGetRequest("https://www.youtube.com/watch?v=" + youTubeId + "&nomobile=1"); request.UserAgent = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"; return Http.Get(request,r => { if (r.Successful) OnHtmlDownloaded(r.Response, minQuality, maxQuality, completed)); else if (completed != null) completed(null, r.Exception); } }
public async Task setVideoSourceAsync(YouTubeQuality videoQuality) { try { var youtubeUrl = await YouTube.GetVideoUriAsync("QTYVJhy04rs", YouTubeQuality.Quality144P, videoQuality); YoutubePlayer.Source = MediaSource.CreateFromUri(youtubeUrl.Uri); YoutubePlayer.AutoPlay = true; } catch (Exception) { //await setVideoSourceAsync(); } }
public static Task<YouTubeUri> GetVideoUriAsync(string youTubeId, YouTubeQuality maxQuality = YouTubeQuality.Quality480P) { var task = new TaskCompletionSource<YouTubeUri>(); GetVideoUri(youTubeId, maxQuality, (u, e) => { if (u != null) task.SetResult(u); else if (e == null) task.SetCanceled(); else task.SetException(e); }); return task.Task; }
public static Task<YouTubeUri> GetVideoUriAsync(string youTubeId, YouTubeQuality maxQuality = YouTubeQuality.Quality360P_MP4) { var task = new TaskCompletionSource<YouTubeUri>(); GetVideoUri(youTubeId, maxQuality, (u, e) => { if (u != null) task.SetResult(u); else if (e == null) task.SetResult(u); //task.SetCanceled(); else task.SetException(e); }); return task.Task; }
/// <summary>Plays the YouTube video in the Windows Phone's external player. </summary> /// <param name="youTubeId">The YouTube ID</param> /// <param name="maxQuality">The maximum allowed video quality. </param> /// <param name="token">The cancellation token</param> /// <returns>Awaitable task. </returns> public static async Task PlayAsync(string youTubeId, YouTubeQuality maxQuality, CancellationToken token) { var uri = await GetVideoUriAsync(youTubeId, maxQuality, token); if (uri != null) { var launcher = new MediaPlayerLauncher { Controls = MediaPlaybackControls.All, Media = uri.Uri }; launcher.Show(); } else { throw new Exception("no_video_urls_found"); } }
public static async void Play(string youTubeId, YouTubeQuality maxQuality, Action <Exception> completed) { try { await PlayAsync(youTubeId, maxQuality); if (completed != null) { completed(null); } } catch (Exception exception) { if (completed != null) { completed(exception); } } }
public static async void Play(string youTubeId, bool manualActivatePage, YouTubeQuality maxQuality, Action <Exception> completed) { try { await PlayWithPageDeactivationAsync(youTubeId, manualActivatePage, maxQuality); if (completed != null) { completed(null); } } catch (Exception exception) { if (completed != null) { completed(exception); } } }
public static int GetQualityIdentifier(YouTubeQuality quality) { switch (quality) { //mp4 case YouTubeQuality.Quality240P_3GP: return 36; case YouTubeQuality.Quality360P_MP4: return 18; case YouTubeQuality.Quality720P_MP4: return 22; case YouTubeQuality.Quality1080P_MP4: return 37; //flv case YouTubeQuality.Quality480P_FLV_44KHZ: return 35; case YouTubeQuality.Quality360P_FLV_22KHZ: return 34; //flv 格式为mp3 case YouTubeQuality.QualityMP3_FLV_44KHZ: return 6; case YouTubeQuality.QualityMP3_FLV_22KHZ: return 5; } throw new ArgumentException("maxQuality"); }
private async void SetVideoUri(string videoId, YouTubeQuality quality, bool isLive) { try { Uri uri = null; if (isLive) { uri = await _getDataSource().GetLiveVideoUriAsync(videoId, quality); } else { var videoUri = await _getDataSource().GetVideoUriAsync(videoId, quality); uri = videoUri?.Uri; } LayoutHelper.InvokeFromUiThread(() => { IsPaid = false; if (uri == null) { return; } VideoUri = uri; }); } //Todo разделить исключения по типу и добавить соответсвующий баннер catch (YouTubeUriNotFoundException) { IsPaid = true; } catch (Exception) { IsPaid = true; } }
private void btnLowQuality_Click(object sender, RoutedEventArgs e) { ResetButtonBackGroundColor(); btnLowQuality.Background = new SolidColorBrush(Colors.Red); VideoQuality = YouTubeQuality.Quality480P; }
/// <summary> /// This method disables the current page and shows a progress indicator until the youtube movie url has been loaded and starts /// </summary> /// <param name="youTubeId"></param> /// <param name="manualActivatePage">if true add YouTube.CancelPlay() in OnNavigatedTo() of the page (better)</param> /// <param name="maxQuality"></param> /// <param name="onFailure"></param> public static void Play(string youTubeId, bool manualActivatePage, YouTubeQuality maxQuality = YouTubeQuality.Quality480P, Action<Exception> onFailure = null) { lock (typeof(YouTube)) { if (oldState != null) return; if (SystemTray.ProgressIndicator == null) SystemTray.ProgressIndicator = new ProgressIndicator(); SystemTray.ProgressIndicator.IsVisible = true; SystemTray.ProgressIndicator.IsIndeterminate = true; var page = PhoneApplication.CurrentPage; oldState = PageDeactivator.Inactivate(); httpResponse = Play(youTubeId, YouTubeQuality.Quality480P, ex => Deployment.Current.Dispatcher.BeginInvoke( delegate { if (page != PhoneApplication.CurrentPage) // user navigated away return; if (ex != null && onFailure != null) { onFailure(ex); CancelPlay(false); } else CancelPlay(manualActivatePage); })); } }
/// <summary>Returns the best matching YouTube stream URI which has an audio and video channel and is not 3D. </summary> /// <returns>The best matching <see cref="YouTubeUri"/> of the video. </returns> /// <exception cref="YouTubeUriNotFoundException">The <see cref="YouTubeUri"/> could not be found. </exception> /// <exception cref="WebException">An error occurred while downloading the resource. </exception> public static Task <YouTubeUri> GetVideoUriAsync(string youTubeId, YouTubeQuality maxQuality, CancellationToken token) { return(GetVideoUriAsync(youTubeId, DefaultMinQuality, maxQuality, token)); }
private static void OnHtmlDownloaded(HttpResponse response, YouTubeQuality quality, Action<Exception> onFinished) { if (response.Successful) { var urls = new List<YouTubeUrl>(); try { var match = Regex.Match(response.Response, "url_encoded_fmt_stream_map=(.*?)(&|\")"); var data = Uri.UnescapeDataString(match.Groups[1].Value); var arr = data.Split(','); foreach (var d in arr) { var tuple = new YouTubeUrl(); foreach (var p in d.Split('&')) { 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") tuple.Url = value; else if (key == "itag") tuple.Itag = int.Parse(value); else if (key == "type" && value.Contains("video/mp4")) tuple.Type = value; } catch { } } } if (tuple.IsValid) urls.Add(tuple); } var itag = GetQualityIdentifier(quality); foreach (var u in urls.Where(u => u.Itag > itag).ToArray()) urls.Remove(u); } catch (Exception ex) { if (onFinished != null) onFinished(ex); return; } var entry = urls.OrderByDescending(u => u.Itag).FirstOrDefault(); if (entry != null) { if (onFinished != null) onFinished(null); var url = entry.Url; var launcher = new MediaPlayerLauncher { Controls = MediaPlaybackControls.All, Media = new Uri(url, UriKind.Absolute) }; launcher.Show(); } else if (onFinished != null) onFinished(new Exception("no_video_urls_found")); } else if (onFinished != null) onFinished(response.Exception); }
/// <summary>Plays the YouTube video in the Windows Phone's external player. /// Disables the current page and shows a progress indicator until /// the YouTube movie URI has been loaded and the video playback starts. </summary> /// <param name="youTubeId">The YouTube ID</param> /// <param name="manualActivatePage">if true add YouTube.CancelPlay() in OnNavigatedTo() of the page (better)</param> /// <param name="maxQuality">The maximum allowed video quality. </param> /// <returns>Awaitable task. </returns> public static async Task PlayWithPageDeactivationAsync(string youTubeId, bool manualActivatePage, YouTubeQuality maxQuality) { PhoneApplicationPage page; lock (typeof(YouTube)) { if (_oldState != null) { return; } if (SystemTray.ProgressIndicator == null) { SystemTray.ProgressIndicator = new ProgressIndicator(); } SystemTray.ProgressIndicator.IsVisible = true; SystemTray.ProgressIndicator.IsIndeterminate = true; page = Environment.PhoneApplication.CurrentPage; _oldState = PageDeactivator.Inactivate(); _cancellationToken = new CancellationTokenSource(); } try { await PlayAsync(youTubeId, maxQuality, _cancellationToken.Token); if (page == Environment.PhoneApplication.CurrentPage) { CancelPlay(manualActivatePage); } } catch (Exception) { if (page == Environment.PhoneApplication.CurrentPage) { CancelPlay(false); } throw; } }
/// <summary>Plays the YouTube video in the Windows Phone's external player. </summary> /// <param name="youTubeId">The YouTube ID</param> /// <param name="maxQuality">The maximum allowed video quality. </param> /// <returns>Awaitable task. </returns> public static Task PlayAsync(string youTubeId, YouTubeQuality maxQuality) { return(PlayAsync(youTubeId, maxQuality, CancellationToken.None)); }
public Task <Uri> GetLiveVideoUriAsync(string videoId, YouTubeQuality quality) { return(new Task <Uri>(() => null)); }
/// <summary> /// Returns the best matching YouTube stream URI which has an audio and video channel and is not 3D. /// </summary> /// <returns>Returns null when no appropriate URI has been found. </returns> public static async Task<YouTubeUri> GetVideoUriAsync(string youTubeId, YouTubeQuality minQuality, YouTubeQuality maxQuality, IResourceNetworkLayer networkLayer, IProgress<float> progress, CancellationToken token) { var uris = await GetUrisAsync(youTubeId, networkLayer, progress, token); return GetBestVideoUri(uris, minQuality, maxQuality); }
private static StreamVideo.VideoQuality GetQuality(YouTubeQuality quality) { return((StreamVideo.VideoQuality)(int) quality); }
public static HttpResponse GetVideoUri(string youTubeId, YouTubeQuality maxQuality, Action<YouTubeUri, Exception> completed) { Debug.WriteLine("GetVideoUri = " + "http://www.youtube.com/watch?v=" + youTubeId); return Http.Get("http://www.youtube.com/watch?v=" + youTubeId, r => OnHtmlDownloaded(r, maxQuality, completed)); }
/// <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(); } } }
/// <summary> /// This method disables the current page and shows a progress indicator until the youtube movie url has been loaded and starts /// </summary> /// <param name="youTubeId"></param> /// <param name="manualActivatePage">if true add YouTube.CancelPlay() in OnNavigatedTo() of the page (better)</param> /// <param name="maxQuality"></param> /// <param name="completed"></param> public static void Play(string youTubeId, bool manualActivatePage, YouTubeQuality maxQuality = YouTubeQuality.Quality480P, Action<Exception> completed = null) { //Debug.WriteLine("Play(string youTubeId, bool manualActivatePage, YouTubeQuality maxQuality = YouTubeQuality.Quality480P, Action<Exception> completed = null)"); lock (typeof(YouTube)) { if (oldState != null) return; if (SystemTray.ProgressIndicator == null) SystemTray.ProgressIndicator = new ProgressIndicator(); SystemTray.ProgressIndicator.IsVisible = true; SystemTray.ProgressIndicator.IsIndeterminate = true; var page = PhonePage.CurrentPage; oldState = PageDeactivator.Inactivate(); httpResponse = Play(youTubeId, YouTubeQuality.Quality480P, ex => Deployment.Current.Dispatcher.BeginInvoke( delegate { if (page == PhonePage.CurrentPage) // !user navigated away CancelPlay(manualActivatePage); if (completed != null) completed(ex); })); } }
/// <summary>Plays the YouTube video in the Windows Phone's external player. </summary> /// <param name="youTubeId">The YouTube ID</param> /// <param name="maxQuality">The maximum allowed video quality. </param> /// <returns>Awaitable task. </returns> public static Task PlayAsync(string youTubeId, YouTubeQuality maxQuality) { return PlayAsync(youTubeId, maxQuality, CancellationToken.None); }
public static HttpResponse Play(string youTubeId, YouTubeQuality maxQuality = YouTubeQuality.Quality480P, Action<Exception> completed = null) { //Debug.WriteLine("GetVideoUri"); return GetVideoUri(youTubeId, maxQuality, (entry, e) => { if (e != null) { if (completed != null) completed(e); } else { if (completed != null) completed(null); if (entry != null) { var launcher = new MediaPlayerLauncher { Controls = MediaPlaybackControls.All, Media = entry.Uri }; Debug.WriteLine("Media URL = " + entry.Uri); launcher.Show(); } } }); }
/// <summary>Plays the YouTube video in the Windows Phone's external player. </summary> /// <param name="youTubeId">The YouTube ID</param> /// <param name="maxQuality">The maximum allowed video quality. </param> /// <param name="token">The cancellation token</param> /// <returns>Awaitable task. </returns> public static async Task PlayAsync(string youTubeId, YouTubeQuality maxQuality, CancellationToken token) { var uri = await GetVideoUriAsync(youTubeId, maxQuality, token); if (uri != null) { var launcher = new MediaPlayerLauncher { Controls = MediaPlaybackControls.All, Media = uri.Uri }; launcher.Show(); } else throw new Exception("no_video_urls_found"); }
public static HttpResponse GetVideoUri(string youTubeId, YouTubeQuality minQuality, YouTubeQuality maxQuality, Action<YouTubeUri, Exception> completed) { return Http.Get("http://www.youtube.com/watch?v=" + youTubeId + "&nomobile=1", r => OnHtmlDownloaded(r, minQuality, maxQuality, completed)); }
/// <summary>Plays the YouTube video in the Windows Phone's external player. /// Disables the current page and shows a progress indicator until /// the YouTube movie URI has been loaded and the video playback starts. </summary> /// <param name="youTubeId">The YouTube ID</param> /// <param name="manualActivatePage">if true add YouTube.CancelPlay() in OnNavigatedTo() of the page (better)</param> /// <param name="maxQuality">The maximum allowed video quality. </param> /// <returns>Awaitable task. </returns> public static async Task PlayWithPageDeactivationAsync(string youTubeId, bool manualActivatePage, YouTubeQuality maxQuality) { PhoneApplicationPage page; lock (typeof(YouTube)) { if (_oldState != null) return; if (SystemTray.ProgressIndicator == null) SystemTray.ProgressIndicator = new ProgressIndicator(); SystemTray.ProgressIndicator.IsVisible = true; SystemTray.ProgressIndicator.IsIndeterminate = true; page = Environment.PhoneApplication.CurrentPage; _oldState = PageDeactivator.Inactivate(); _cancellationToken = new CancellationTokenSource(); } try { await PlayAsync(youTubeId, maxQuality, _cancellationToken.Token); if (page == Environment.PhoneApplication.CurrentPage) CancelPlay(manualActivatePage); } catch (Exception) { if (page == Environment.PhoneApplication.CurrentPage) CancelPlay(false); throw; } }
public static HttpResponse GetVideoUri(string youTubeId, YouTubeQuality maxQuality, Action<YouTubeUri, Exception> completed) { return GetVideoUri(youTubeId, YouTubeQuality.Quality480P, maxQuality, completed); }
public async Task <Uri> GetLiveVideoUriAsync(string videoId, YouTubeQuality quality) { return(await _remoteDataSource.GetLiveVideoUriAsync(videoId, quality)); }
private static void OnHtmlDownloaded(HttpResponse response, YouTubeQuality minQuality, YouTubeQuality maxQuality, Action<YouTubeUri, Exception> completed) { if (response.Successful) { var urls = new List<YouTubeUri>(); try { var match = Regex.Match(response.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")) tuple.Type = 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()) 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")); } else if (completed != null) completed(null, response.Exception); }
public static async void Play(string youTubeId, YouTubeQuality maxQuality, Action<Exception> completed) { try { await PlayAsync(youTubeId, maxQuality); if (completed != null) completed(null); } catch (Exception exception) { if (completed != null) completed(exception); } }
public static HttpResponse Play(string youTubeId, YouTubeQuality maxQuality = YouTubeQuality.Quality480P, Action<Exception> onFinished = null) { return Http.Get("http://www.youtube.com/watch?v=" + youTubeId, r => OnHtmlDownloaded(r, maxQuality, onFinished)); }
public static async void Play(string youTubeId, bool manualActivatePage, YouTubeQuality maxQuality, Action<Exception> completed) { try { await PlayWithPageDeactivationAsync(youTubeId, manualActivatePage, maxQuality); if (completed != null) completed(null); } catch (Exception exception) { if (completed != null) completed(exception); } }
/// <summary>Returns the best matching YouTube stream URI which has an audio and video channel and is not 3D. </summary> /// <returns>The best matching <see cref="YouTubeUri"/> of the video. </returns> /// <exception cref="YouTubeUriNotFoundException">The <see cref="YouTubeUri"/> could not be found. </exception> /// <exception cref="WebException">An error occurred while downloading the resource. </exception> public static Task <YouTubeUri> GetVideoUriAsync(string youTubeId, YouTubeQuality minQuality, YouTubeQuality maxQuality) { return(GetVideoUriAsync(youTubeId, minQuality, maxQuality, CancellationToken.None)); }
/// <summary>Returns the best matching YouTube stream URI which has an audio and video channel and is not 3D. </summary> /// <returns>The best matching <see cref="YouTubeUri"/> of the video. </returns> /// <exception cref="YouTubeUriNotFoundException">The <see cref="YouTubeUri"/> could not be found. </exception> /// <exception cref="WebException">An error occurred while downloading the resource. </exception> public static Task<YouTubeUri> GetVideoUriAsync(string youTubeId, YouTubeQuality maxQuality, CancellationToken token) { return GetVideoUriAsync(youTubeId, DefaultMinQuality, maxQuality, token); }
public static HttpResponse GetVideoUri(string youTubeId, YouTubeQuality maxQuality, Action<YouTubeUri, Exception> completed) { return GetVideoUri(youTubeId, YouTubeQuality.QualityMP3_FLV_22KHZ, maxQuality, completed); }
/// <summary>Returns the best matching YouTube stream URI which has an audio and video channel and is not 3D. </summary> /// <returns>The best matching <see cref="YouTubeUri"/> of the video. </returns> /// <exception cref="YouTubeUriNotFoundException">The <see cref="YouTubeUri"/> could not be found. </exception> /// <exception cref="WebException">An error occurred while downloading the resource. </exception> public static Task<YouTubeUri> GetVideoUriAsync(string youTubeId, YouTubeQuality minQuality, YouTubeQuality maxQuality) { return GetVideoUriAsync(youTubeId, minQuality, maxQuality, CancellationToken.None); }
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); }
public Task <YouTubeUri> GetVideoUriAsync(string videoId, YouTubeQuality quality) { return(Task.Run(() => { return new YouTubeUri(); })); }
private static void OnHtmlDownloaded(HttpResponse response, YouTubeQuality quality, Action<YouTubeUri, Exception> completed) { if (response.Successful) { var urls = new List<YouTubeUri>(); try { //Debug.WriteLine("match = " + response.Response.ToString()); //var match = Regex.Match(response.Response, "url_encoded_fmt_stream_map=(.*?)(&|\")"); //var data = Uri.UnescapeDataString(match.Groups[1].Value); var match = Regex.Match(response.Response, @"url_encoded_fmt_stream_map\"":(.*)\"""); String a = match.Groups[1].Value; var data = a.Replace("\\u0026", "&"); var arr = data.Split(','); foreach (var d in arr) { var url = ""; var signature = ""; var tuple = new YouTubeUri(); foreach (var p in d.Split('&')) { 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")) tuple.Type = value; else if (key == "sig") signature = value; } catch { } } } tuple.url = url + "&signature=" + signature; if (tuple.IsValid) urls.Add(tuple); } var itag = GetQualityIdentifier(quality); foreach (var u in urls.Where(u => u.Itag > itag).ToArray()) urls.Remove(u); } catch (Exception ex) { if (completed != null) completed(null, ex); return; } Debug.WriteLine("entry = " + urls.OrderByDescending(u => u.Itag).FirstOrDefault().ToString()); 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")); } else if (completed != null) completed(null, response.Exception); }
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(); } }
private static YouTubeUri TryFindBestVideoUri(IEnumerable<YouTubeUri> uris, YouTubeQuality minQuality, YouTubeQuality maxQuality) { return uris .Where(u => u.HasVideo && u.HasAudio && !u.Is3DVideo && u.VideoQuality >= minQuality && u.VideoQuality <= maxQuality) .OrderByDescending(u => u.VideoQuality) .FirstOrDefault(); }
/// <summary> /// Returns the best matching YouTube stream URI which has an audio and video channel and is not 3D. /// </summary> /// <returns>Returns null when no appropriate URI has been found. </returns> public static Task<YouTubeUri> GetVideoUriAsync(string youTubeId, YouTubeQuality maxQuality, IResourceNetworkLayer networkLayer, IProgress<float> progress, CancellationToken token) { return GetVideoUriAsync(youTubeId, DefaultMinQuality, maxQuality, networkLayer, progress, token); }