Пример #1
0
        private async void Button1_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog fbd = new FolderBrowserDialog()
            {
                Description = "Select Path"
            })
            {
                if (textBox1.Text != "")
                {
                    if (fbd.ShowDialog() == DialogResult.OK)
                    {
                        var          youtube = YouTube.Default;
                        YouTubeVideo video   = await youtube.GetVideoAsync(textBox1.Text);

                        string filename = "";
                        string ending   = comboBox1.SelectedItem.ToString();
                        setName(filename, video.FullName, ending);

                        using (WebClient client = new WebClient())
                        {
                            client.DownloadFileCompleted   += client_Completed;
                            client.DownloadProgressChanged += dlProgressChange;
                            client.DownloadFileAsync(new Uri(video.GetUri()), fbd.SelectedPath + @"\" + getName());
                            //File.WriteAllBytes(fbd.SelectedPath + @"\" + filename, await video.GetBytesAsync());
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Enter valid URL");
                }
            }
        }
        private void getMetaData()
        {
            YouTube     youtube = YouTube.Default;
            ReturnError results = new ReturnError();

            try
            {
                YouTubeVideo audio =
                    youtube.GetAllVideos(_link)
                    //.Where(e => e.AudioFormat == AudioFormat.Aac && e.AdaptiveKind == AdaptiveKind.Audio)
                    .ToList()
                    .FirstOrDefault();

                string filename = audio.FullName.Replace(" - YouTube", "");
                filename = filename.Replace(".mp4", "");

                MediaFile inputFile = new MediaFile {
                    Filename = audio.GetUri()
                };

                using (Engine engine = new Engine())
                {
                    engine.GetMetadata(inputFile);
                    video.VideoName = filename;

                    if (inputFile.Metadata.Duration.ToString().StartsWith("00"))
                    {
                        video.Length = inputFile.Metadata.Duration.ToString().Substring(3, 5);
                    }
                    else
                    {
                        video.Length = inputFile.Metadata.Duration.ToString().Substring(0, 8);
                    }
                }
            }
            catch (NullReferenceException e)
            {
                results.errorNumber++;
                results.errorLinks.Add(_link);
            }
        }
Пример #3
0
        /// <summary>
        /// Get the MediaSource of the specified youtube video, preferring audio stream to video
        /// </summary>
        /// <param name="videoId">The id of the video to get audio for</param>
        /// <returns>The audio of the track</returns>
        private async Task <MediaSource> GetAudioAsync(string videoId, string trackName)
        {
            IEnumerable <YouTubeVideo> videos = await YouTube.Default.GetAllVideosAsync(string.Format(_videoUrlFormat, videoId));

            YouTubeVideo maxAudioVideo    = null;
            YouTubeVideo maxNonAudioVideo = null;

            try
            {
                for (int i = 0; i < videos.Count(); i++)
                {
                    YouTubeVideo video = videos.ElementAt(i);
                    if (video.AdaptiveKind == AdaptiveKind.Audio)
                    {
                        if (maxAudioVideo == null || video.AudioBitrate > maxAudioVideo.AudioBitrate)
                        {
                            maxAudioVideo = video;
                        }
                    }
                    else
                    {
                        if (maxNonAudioVideo == null || video.AudioBitrate > maxNonAudioVideo.AudioBitrate)
                        {
                            maxNonAudioVideo = video;
                        }
                    }
                }
            }
            catch (HttpRequestException)
            {
                try
                {
                    return(MediaSource.CreateFromUri(new Uri(videos.ElementAt(0).GetUri())));
                }
                catch (Exception)
                {
                    return(MediaSource.CreateFromUri(new Uri("")));
                }
            }
            if (maxAudioVideo != null)
            {
                return(MediaSource.CreateFromUri(new Uri(maxAudioVideo.GetUri())));
            }
            else if (maxNonAudioVideo != null)
            {
                HttpClientHandler handler = new HttpClientHandler()
                {
                    AllowAutoRedirect = true
                };
                HttpClient client = new HttpClient(handler);

                CancellationTokenSource cancelToken = new CancellationTokenSource();
                cancelToken.Token.Register(() =>
                {
                    client.CancelPendingRequests();
                    client.Dispose();
                    App.mainPage.HideCancelDialog(localLock);
                });

                try
                {
                    Task <HttpResponseMessage> clientTask = client.GetAsync(new Uri(maxNonAudioVideo.GetUri()), HttpCompletionOption.ResponseContentRead, cancelToken.Token);
                    Task completedTask = await Task.WhenAny(clientTask, Task.Delay(5000));

                    if (completedTask != clientTask)
                    {
                        if (App.isInBackgroundMode)
                        {
                            cancelToken.Cancel();
                            return(MediaSource.CreateFromUri(new Uri("")));
                        }
                        else
                        {
                            App.mainPage.ShowCancelDialog(localLock, cancelToken, trackName);
                            await Task.Run(() =>
                            {
                                while ((clientTask.Status == TaskStatus.WaitingForActivation ||
                                        clientTask.Status == TaskStatus.WaitingForChildrenToComplete ||
                                        clientTask.Status == TaskStatus.WaitingToRun ||
                                        clientTask.Status == TaskStatus.Running) && !cancelToken.Token.IsCancellationRequested)
                                {
                                }
                            });

                            App.mainPage.HideCancelDialog(localLock);
                            if (cancelToken.Token.IsCancellationRequested)
                            {
                                return(MediaSource.CreateFromUri(new Uri("")));
                            }
                        }
                    }
                    HttpResponseMessage response = clientTask.Result;
                    Stream stream = await response.Content.ReadAsStreamAsync();

                    return(MediaSource.CreateFromStream(stream.AsRandomAccessStream(), "video/x-flv"));
                }
                catch (OperationCanceledException)
                {
                    return(MediaSource.CreateFromUri(new Uri("")));
                }
            }
            return(MediaSource.CreateFromUri(new Uri("")));
        }
        public ReturnError DownloadMP3(List <string> links, string destPath)
        {
            _songCount = links.Count;
            if (_songCount == 0)
            {
                throw new Exception("No links available.");
            }
            if (!Directory.Exists(destPath))
            {
                throw new DirectoryNotFoundException("Destination path does not exist.");
            }

            YouTube youtube = YouTube.Default;

            convertedSong = 0;
            ReturnError results = new ReturnError();

            results.errorNumber = 0;
            results.errorLinks  = new List <string>();
            foreach (string link in links)
            {
                if (link.Contains("&list="))
                {
                    downloadPlaylist(link, destPath, "", 0);
                }
                else
                {
                    try
                    {
                        YouTubeVideo audio =
                            youtube.GetAllVideos(link)
                            .Where(e => e.AudioFormat == AudioFormat.Aac && e.AdaptiveKind == AdaptiveKind.Audio)
                            .ToList()
                            .FirstOrDefault();

                        string filename =
                            Path.ChangeExtension(
                                Path.Combine(destPath, Path.GetFileNameWithoutExtension(audio.FullName)),
                                "mp3");
                        filename = filename.Replace(" - YouTube", "");

                        MediaFile inputFile = new MediaFile {
                            Filename = audio.GetUri()
                        };
                        MediaFile outputFile = new MediaFile {
                            Filename = filename
                        };

                        getThumbnail(link);

                        using (Engine engine = new Engine())
                        {
                            engine.GetMetadata(inputFile);
                            engine.Convert(inputFile, outputFile);
                            engine.ConvertProgressEvent += engine_ConvertProgressEvent;
                        }
                    }
                    catch (NullReferenceException e)
                    {
                        results.errorNumber++;
                        results.errorLinks.Add(link);
                    }
                }
            }
            return(results);
        }