/// <summary> /// Downloads context to audio, requires Url, Optional - VideoInfo (Default: Highest Quality), Optional - BaseDirectory /// </summary> public static void ToVideo(this YoutubeContext context, VideoType customtype = VideoType.Mp4) { if (context==null) throw new ArgumentException(nameof(context)); if (string.IsNullOrEmpty(context.Url)) throw new ArgumentException(nameof(context.Url)); if (context.VideoInfo == null) context.FindHighestVideoQualityDownloadUrl(customtype); var vd = new VideoDownloader(context); vd.Execute(); }
private void btnDownload_Click(object sender, EventArgs e) { ProgressBar.Minimum = 0; ProgressBar.Maximum = 100; IEnumerable <VideoInfo> vid = DownloadUrlResolver.GetDownloadUrls(textUrl.Text); //It doesn't work for some URLs VideoInfo video = vid.First(n => n.VideoType == VideoType.Mp4 && n.Resolution == Convert.ToInt32(ComboBoxResolution.Text)); if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } VideoDownloader dLoader = new VideoDownloader(video, Path.Combine(Application.StartupPath + "\\", video.Title + video.VideoExtension)); dLoader.DownloadProgressChanged += Downloader_DownloadProgressCHanged; Thread thread = new Thread(() => { dLoader.Execute(); }) { IsBackground = true }; thread.Start(); }
public void Download(VideoInfo video) { //bool answer = UserInterface.IsVideo(); if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } VideoDownloader videoDownloader = new VideoDownloader(video, Path.Combine(VideoSavePath, video.Title + video.VideoExtension)); videoDownloader.DownloadProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage); videoDownloader.Execute(); /// TODO: Reimplement the audio to video converter. //if (!answer) //{ VideoToAudioConverter converter = new VideoToAudioConverter(VideoSavePath, video.Title, video.VideoExtension); converter.ConvertVideoToAudioFile(); DeleteFile(VideoSavePath + @"\" + video.Title + video.VideoExtension); //} }
private async static void DownloadAudio(string URL) { string link = URL; IEnumerable <YoutubeExtractor.VideoInfo> videoInfos = null; try { videoInfos = DownloadUrlResolver.GetDownloadUrls(link); MediaMessage = await TextChannel.SendMessage("Downloading audio..."); } catch (Exception) { await MediaMessage.Delete(); await User.SendMessage("Invalid link :("); return; } VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 0); mediaName = video.Title; audioPath = Path.Combine(Environment.CurrentDirectory, "files", "audio", video.Title + video.AudioExtension); mp3Path = Path.Combine(Environment.CurrentDirectory, "files", "mp3", video.Title + ".mp3"); var audioDownloader = new VideoDownloader(video, audioPath); audioDownloader.DownloadFinished += AudioDownloader_DownloadFinished; try { audioDownloader.Execute(); } catch (Exception e) { Bot.NotifyDevs(Supporter.BuildExceptionMessage(e, "DownloadAudio()", URL)); await MediaMessage.Edit("Failed downloading audio"); } }
private static void RunDownload(string url, string path, int resolution, string videoType, string audioType) { videoType = videoType ?? VideoType.Mp4.ToString(); audioType = audioType ?? AudioType.Aac.ToString(); var videoInfos = DownloadUrlResolver.GetDownloadUrls(url, false).ToList(); var cc = videoInfos.OrderBy(it => Math.Abs(it.Resolution - resolution)).ToList(); if (videoType != null && cc.Any(it => it.VideoType.ToString() == videoType)) { cc = cc.Where(it => it.VideoType.ToString() == videoType).ToList(); } if (audioType != null && cc.Any(it => it.AudioType.ToString() == audioType)) { cc = cc.Where(it => it.AudioType.ToString() == audioType).ToList(); } VideoInfo video = cc.First(); if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } if (string.IsNullOrEmpty(path)) { var chars = Path.GetInvalidPathChars().Concat(Path.GetInvalidFileNameChars()).ToArray(); path = "[" + video.VideoId + "]" + string.Join("_", video.Title.Split(chars)) + ".mp4"; } Console.WriteLine(path); var videoDownloader = new VideoDownloader(video, path); videoDownloader.Execute(); }
public void downloadVideo() { //begin by getting the selected video, aka history at slot 0 VideoInfo vid = history.ElementAt(0).info; //deal with any present decrypted signatures if (vid.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(vid); } //before processing, make sure to hide the button //OR make a modal that blocks the screen from the user //call to download, wait for the download to finish var videoDownloader = new VideoDownloader(vid, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), RemoveIllegalPathCharacters(vid.Title) + vid.VideoExtension)); videoDownloader.Execute(); //unhide button after video finishes //OR remove the modal }
public static void DownloadVideo(string videoLink, string saveLocation, Resolution resolution) { var video = GetVideo(videoLink, resolution); /* * If the video has a decrypted signature, decipher it */ if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } /* * Create the video downloader. * The first argument is the video to download. * The second argument is the path to save the video file. */ var path = saveLocation != "" ? saveLocation : Environment.GetFolderPath(Environment.SpecialFolder.MyVideos); var videoDownloader = new VideoDownloader(video, Path.Combine(path, RemoveIllegalPathCharacters(video.Title) + video.VideoExtension)); // Register the ProgressChanged event and print the current progress videoDownloader.DownloadProgressChanged += (sender, args) => CurrentDownloadProgress.CurrentProgress = args.ProgressPercentage; /* * Execute the video downloader. * For GUI applications note, that this method runs synchronously. */ videoDownloader.Execute(); }
private void Download(string link) { int index = link.IndexOf('='); string id = link.Remove(0, index + 1); label3.Text = "Loading..."; IEnumerable <VideoInfo> videoinfos = DownloadUrlResolver.GetDownloadUrls("https://www.youtube.com/watch?v=" + id); VideoInfo video = videoinfos.First(); if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } VideoDownloader videoDownloader; String name; if (String.IsNullOrWhiteSpace(textBox2.Text)) { name = video.Title; } else { name = textBox2.Text; } videoDownloader = new VideoDownloader(video, Path.Combine(Application.StartupPath, name + video.VideoExtension)); currentlyDownloading.Text = video.Title; label3.Text = "Downloading..."; videoDownloader.DownloadProgressChanged += (sender, args) => barchange(sender, args); videoDownloader.DownloadFinished += (sender, args) => Convert(Path.Combine(Application.StartupPath, name + video.VideoExtension), name); Thread download = new Thread(() => { videoDownloader.Execute(); }) { IsBackground = true }; download.Start(); }
async Task Download(string destinationFolder) { Progress = 0; IsDownloading = true; try { await Task.Run(() => { var videoInfos = DownloadUrlResolver.GetDownloadUrls(SourceAddress); var video = videoInfos.FirstOrDefault(info => info.VideoType == VideoType.Mp4); if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } var invalidChars = Path.GetInvalidFileNameChars(); var fileName = (video.Title + video.VideoExtension).Where(c => !invalidChars.Contains(c)).JoinStrings(); var videoDownloader = new VideoDownloader(video, Path.Combine(destinationFolder, fileName)); videoDownloader.DownloadProgressChanged += (sender, args) => Progress = args.ProgressPercentage; Observable.FromEventPattern <EventHandler <ProgressEventArgs>, ProgressEventArgs> (h => videoDownloader.DownloadProgressChanged += h, h => videoDownloader.DownloadProgressChanged -= h) .Throttle(TimeSpan.FromMilliseconds(100)) .ObserveOn(App.Current.Dispatcher) .Subscribe(a => Progress = a.EventArgs.ProgressPercentage); videoDownloader.Execute(); }); } catch (Exception e) { MessageBox.Show("Download failed!"); } }
private static void DownloadVideo(IEnumerable <VideoInfo> videoInfos) { /* * Select the first .mp4 video with 360p resolution */ VideoInfo video = videoInfos .First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 360); /* * Create the video downloader. * The first argument is the video to download. * The second argument is the path to save the video file. */ var videoDownloader = new VideoDownloader(video, Path.Combine("D:/Downloads", video.Title + video.VideoExtension)); // Register the ProgressChanged event and print the current progress videoDownloader.DownloadProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage); /* * Execute the video downloader. * For GUI applications note, that this method runs synchronously. */ videoDownloader.Execute(); }
static async void DownloadVideo(string videoID) { Directory.CreateDirectory("Downloads/"); IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls("https://www.youtube.com/watch?v=" + videoID); VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 720); if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } var videoDownloader = new VideoDownloader(video, Path.Combine("Downloads/", RemoveIllegalPathCharacters(video.Title) + video.VideoExtension)); videoDownloader.DownloadStarted += (sender, argss) => Console.WriteLine("Started downloading " + video.Title + video.VideoExtension); videoDownloader.DownloadProgressChanged += (sender, argss) => { Console.WriteLine(argss.ProgressPercentage); }; videoDownloader.DownloadFinished += (sender, argss) => Console.WriteLine("Finished downloading " + video.Title + video.VideoExtension); videoDownloader.Execute(); }
static Song downloadVid(string link) { IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link); VideoInfo video = videoInfos .First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 360); if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } Song temp = new Song(video.Title, "0", " "); temp.song = new MemoryStream(); if (!System.IO.File.Exists(Path.Combine(@"C:\Users\thoma\Documents\Visual Studio 2015\Projects\EmoticonBot\EmoticonBot\audio", video.Title + video.VideoExtension))) { var videoDownloader = new VideoDownloader(video, Path.Combine(@"C:\Users\thoma\Documents\Visual Studio 2015\Projects\EmoticonBot\EmoticonBot\audio\", video.Title + video.VideoExtension)); videoDownloader.Execute(); var file = TagLib.File.Create(Path.Combine(@"C:\Users\thoma\Documents\Visual Studio 2015\Projects\EmoticonBot\EmoticonBot\audio", video.Title + video.VideoExtension)); //temp.duration = (file.Properties.Duration.Minutes * 60) + file.Properties.Duration.Seconds; return(temp); } return(temp); }
private static void DownloadAudioVideo(IEnumerable <VideoInfo> videoInfos) { /* * We want the first extractable video with the highest audio quality. */ VideoInfo video = videoInfos .Where(info => info.AdaptiveType == AdaptiveType.Audio_Video) .OrderByDescending(info => info.AudioBitrate) .First(); /* * If the video has a decrypted signature, decipher it */ if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } /* * Create the video downloader. * The first argument is the video to download. * The second argument is the path to save the video file. */ var videoDownloader = new VideoDownloader(video, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), RemoveIllegalPathCharacters(video.Title) + video.VideoExtension)); // Register the ProgressChanged event and print the current progress videoDownloader.DownloadProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage); /* * Execute the video downloader. * For GUI applications note, that this method runs synchronously. */ videoDownloader.Execute(); }
/// <summary> /// Entry method for the console app. /// </summary> /// <param name="args">The arguments.</param> public static void Main(string[] args) { var downloader = new ytgify.Adapters.YoutubeExtractorWrapper.YoutubeExtractorAdapter(); var info2 = downloader.GetVideoInfos(new Uri("https://www.youtube.com/watch?v=FaOSCASqLsE")); downloader.Download(info2.First(), "vidya.mp4"); var adapt = new FFMpegVideoToGifAdapter(); adapt.Convert( @"C:\dev\git\ytgify\ytgifyConsole\bin\Debug\Star Wars Undercover Boss_ Starkiller Base - SNL.mp4", Guid.NewGuid() + ".gif", new GifyRequest { StartTime = new TimeSpan(0, 1, 50), CaptureLengthTime = new TimeSpan(0, 0, 8), }); ////var link = "https://www.youtube.com/watch?v=2a4gyJsY0mc"; var link = "https://www.youtube.com/watch?v=FaOSCASqLsE"; var videoInfos = DownloadUrlResolver.GetDownloadUrls(link); videoInfos = videoInfos.Where(v => v.Resolution > 300).OrderBy(v => v.Resolution); var video = videoInfos.First(info => info.VideoType == VideoType.Mp4); if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } var fname = video.Title; var badChars = Path.GetInvalidFileNameChars().Where(c => fname.Contains(c)); foreach (var badChar in badChars) { fname = fname.Replace(badChar, '_'); } var videoDownloader = new VideoDownloader(video, Path.Combine(Environment.CurrentDirectory, fname + video.VideoExtension)); videoDownloader.Execute(); var reader = new VideoFileReader(); reader.Open(Path.Combine(Environment.CurrentDirectory, fname + video.VideoExtension)); var framesToSkip = 110 * 23.98; // reader.FrameRate; for (int i = 0; i < framesToSkip; i++) { var fr = reader.ReadVideoFrame(); fr.Dispose(); } var framesToTake = 7 * 23.98; var outputFilePath = Path.Combine(Environment.CurrentDirectory, "screen.gif"); var e = new AnimatedGifEncoder(); e.Start(outputFilePath); e.SetDelay(1000 / 24); e.SetRepeat(0); for (int i = 0; i < framesToTake; i++) { var videoFrame = reader.ReadVideoFrame(); e.AddFrame(videoFrame); videoFrame.Dispose(); } reader.Close(); for (int i = 0; i < framesToTake; i++) { ////e.AddFrame(Image.FromFile(Path.Combine(Environment.CurrentDirectory, "screenie" + i + ".png"))); } e.Finish(); }
static void Main(string[] args) { string baseDir = AppDomain.CurrentDomain.BaseDirectory; //Ask what account to retrieve playlists from Console.WriteLine("Enter the ID of the account you want to consult the playlists : "); Spotify spot = new Spotify(Console.ReadLine()); //Get the id of the playlist do download var pl = spot.GetPlaylistsNames(); int id = -1; while (id < 0 || id >= pl.Count()) { Console.WriteLine("Select the playlist that you want to download : "); for (int i = 0; i < pl.Count(); i++) { Console.WriteLine(i.ToString() + ". " + pl[i]); } string tmp = Console.ReadLine(); int tmp2 = -1; if (int.TryParse(tmp, out tmp2)) { id = Convert.ToInt32(tmp); } } //Get the tracks of the selectioned playlist var playlistTracks = spot.GetPlaylistTrackById(id); //Get the name of the playlist string plName = pl[id].Trim(); Console.WriteLine("Downloading : " + plName); //Create a folder with the name of the playlist of one doesn't already exists if (!System.IO.File.Exists(plName)) { Directory.CreateDirectory(plName); } var items = new VideoSearch(); //Is used to count the number of downloaded tracks int c = 1; //Goes through each song foreach (var song in playlistTracks) { string songName = ClearChars(song.Track.Name + " - " + song.Track.Artists[0].Name); foreach (var item in items.SearchQuery(songName, 1)) { string link = item.Url; bool done = false; //Youtube extractor - Get the infos on the video IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link); VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 360); if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } var videoDownloader = new VideoDownloader(video, Path.Combine(plName, songName + video.VideoExtension)); //Try to download the video try { videoDownloader.Execute(); done = true; } catch (Exception) { } //If the video was downloaded succesfully if (done) { //Set all the paths string p1 = Path.Combine(baseDir, plName, songName + ".mp4"); string p2 = Path.Combine(baseDir, plName, songName + ".mp3"); var inputFile = new MediaFile { Filename = p1 }; var outputFile = new MediaFile { Filename = p2 }; using (var engine = new Engine()) { //Convert the video to mp3 then deletes it engine.Convert(inputFile, outputFile); } System.IO.File.Delete(p1); //Set the mp3 tags for artists and title TagLib.File file = TagLib.File.Create(p2); file.Tag.Performers = ((IEnumerable <SimpleArtist>)song.Track.Artists).Select(p => p.Name).ToArray(); file.Tag.Title = song.Track.Name; file.Tag.Album = song.Track.Album.Name; file.Save(); Console.WriteLine(string.Format("{0} : downloaded. {1}/{2}", songName, c.ToString(), playlistTracks.Count.ToString())); c++; break; } } } Console.WriteLine("Done! You can find your songs in the \"" + plName + "\" folder in the root of the application."); Process.Start(Path.Combine(baseDir, plName)); Console.Read(); }
//NotificationWin w = new NotificationWin(); public VideoDownloader VideoDownloader(string url, VideoExtensionType videoExtensionType, string videoPath = "") { VideoDownloader downloader = null; try { IEnumerable <VideoInfo> videos = DownloadUrlResolver.GetDownloadUrls(url); //Get url video VideoInfo video; if (videoExtensionType != null) { video = videos.First(p => p.VideoExtension == videoExtensionType.VideoExtension && p.Resolution == videoExtensionType.Resolution); } else { video = videos.FirstOrDefault(a => a.VideoType == VideoType.Mp4); } if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } if (string.IsNullOrWhiteSpace(videoPath)) { videoPath = System.AppDomain.CurrentDomain.BaseDirectory + "\\Download\\"; } var titel = Porter.Model.Helper.RemoveSpatialCharacter(video.Title); if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } //Download video downloader = new VideoDownloader(video, videoPath + titel + video.VideoExtension); //removeExistFile(videoPath + titel, video.VideoExtension); downloader.DownloadProgressChanged += Downloader_DownloadProgressChanged; downloader.DownloadFinished += Downloader_DownloadFinished; ////Create a new thread to download file Task task = new Task(() => { try { downloader.Execute(); } catch (Exception) { sadyoutube(url); } }); // { IsBackground = true }; task.Start(); } catch (YoutubeParseException ex) { sadyoutube(url); } catch (Exception) { } return(downloader); }
private void btnDownload_Click(object sender, RoutedEventArgs e) { lblMsg.Content = "Download started"; if (rbvideo.IsChecked == true) // because nullable { System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { if (viVideo.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(viVideo); } var videoDownloader = new VideoDownloader(viVideo, System.IO.Path.Combine(tbDir.Text, SafeFileName(viVideo.Title) + viVideo.VideoExtension)); videoDownloader.DownloadProgressChanged += (s, args) => lblMsg.Content = args.ProgressPercentage; try { videoDownloader.Execute(); lblMsg.Content = "Completed!"; Process.Start(tbDir.Text); } catch (UnauthorizedAccessException uae) { Console.WriteLine(uae.Message); Console.WriteLine(uae.StackTrace); lblMsg.Content = "You are not allowed to write in this folder, please select an other destination folder to store the video"; } })); } else { System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { if (viAudio.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(viAudio); } var videoDownloader = new VideoDownloader(viAudio, System.IO.Path.Combine(tbDir.Text, SafeFileName(viAudio.Title) + ".M4A")); videoDownloader.DownloadProgressChanged += (s, args) => lblMsg.Content = args.ProgressPercentage; try { videoDownloader.Execute(); ProcessAudio(System.IO.Path.Combine(tbDir.Text, SafeFileName(viAudio.Title) + ".M4A")); lblMsg.Content = "Completed!"; Process.Start(tbDir.Text); } catch (UnauthorizedAccessException uae) { Console.WriteLine(uae.Message); Console.WriteLine(uae.StackTrace); lblMsg.Content = "You are not allowed to write in this folder, please select an other destination folder to store the video"; } catch (IOException ioe) { Console.WriteLine(ioe.Message); Console.WriteLine(ioe.StackTrace); } catch (WebException wex) { Console.WriteLine(wex.Message); Console.WriteLine(wex.StackTrace); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } })); } }
private void btnDowload_Click(object sender, EventArgs e) { if (textBoxUrl.Text == "") { MessageBox.Show("No YouTube video url found. Paste/Type the YouTube video url please!", "Paste/Type The YouTube Video Url.", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (textBoxUrl.Text.Contains("www.youtube.com/") || textBoxUrl.Text.Contains("WWW.YOUTUBE.COM/") || textBoxUrl.Text.Contains("youtube.com/") || textBoxUrl.Text.Contains("YOUTUBE.COM/") || textBoxUrl.Text.Contains("youtu.be/") || textBoxUrl.Text.Contains("YOUTU.BE/") || textBoxUrl.Text.Contains("www.youtu.be/") || textBoxUrl.Text.Contains("WWW.YOUTU.BE/")) { if (textBoxPath.Text != "") { statusPanel1.BorderStyle = StatusBarPanelBorderStyle.Sunken; statusPanel1.Text = "Status: Connecting to YouTube..."; statusPanel1.ToolTipText = "Current Activity"; statusPanel1.AutoSize = StatusBarPanelAutoSize.Spring; progressBar.Minimum = 0; progressBar.Maximum = 100; try { IEnumerable <VideoInfo> videos = DownloadUrlResolver.GetDownloadUrls(textBoxUrl.Text); VideoInfo video = videos.First(p => p.VideoType == VideoType.Mp4 && p.Resolution == Convert.ToInt32(comboBoxQuality.Text)); if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } VideoDownloader downloader = new VideoDownloader(video, Path.Combine(textBoxPath.Text, video.Title + video.VideoExtension)); downloader.DownloadProgressChanged += Downloader_DownloadProgressChanged; Thread thread = new Thread(() => { downloader.Execute(); }) { IsBackground = true }; thread.Start(); statusPanel1.BorderStyle = StatusBarPanelBorderStyle.Sunken; statusPanel1.Text = "Status: Downloading: " + video.Title + video.VideoExtension; statusPanel1.ToolTipText = "Current Activity"; statusPanel1.AutoSize = StatusBarPanelAutoSize.Spring; } catch (Exception) { DialogResult Response = MessageBox.Show("Connection failed. Check the connection settings and try again!", "Connection Failed", MessageBoxButtons.OK, MessageBoxIcon.Error); if (Response == DialogResult.OK) { textBoxUrl.Text = ""; progressBar.Value = 0; lblPercentage.Text = "0%"; textBoxPath.Text = ""; comboBoxQuality.SelectedIndex = 2; statusPanel1.BorderStyle = StatusBarPanelBorderStyle.Sunken; statusPanel1.Text = "Status: No video to download. Paste the video url and download the video."; statusPanel1.ToolTipText = "Current Activity"; statusPanel1.AutoSize = StatusBarPanelAutoSize.Spring; } } } else { MessageBox.Show("No storage location found. Select where the video will be saved please!", "Video Storage Location", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else { MessageBox.Show("Invalid YouTube video url. Paste/Type the right YouTube video url please!", "Paste/Type The Right YouTube Video Url.", MessageBoxButtons.OK, MessageBoxIcon.Warning); textBoxUrl.Text = ""; } }
public static async Task <string> DownloadVideo(ChromiumWebBrowser youtubePlayer) { #if USE_YOUTUBE_EXTRACTOR string link = "https://www.youtube.com/watch?v=" + Music.VideoId; IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link); VideoInfo video = videoInfos .First(info => info.VideoType == VideoType.WebM && info.Resolution == 360); if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } var fullName = video.Title; var saveName = fullName.Replace("- YouTube", ""); var videoDownloader = new VideoDownloader(video, Path.Combine(FilePaths.SaveLocation(), FilePaths.RemoveIllegalPathCharacters(saveName))); videoDownloader.DownloadProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage); videoDownloader.Execute(); #endif #if USE_LIBVIDEO /*// Other youtube library libvideo * var uri = "https://www.youtube.com/watch?v=" + Music.VideoId; * var youTube = YouTube.Default; * var video = youTube.GetVideo(uri);*///youtubePlayer.Address = "http://33232463.nhd.weebly.com/"; /*var fullName = video.FullName; // same thing as title + fileExtension * var saveName = FilePaths.RemoveIllegalPathCharacters(fullName.Replace("- YouTube", "")); * saveName = saveName.Replace("_", ""); * var bytes = await video.GetBytesAsync(); * //var stream = video.Stream();*/ #endif #if USE_YOUTUBEEXPLODE // Client var client = new YoutubeClient(); var videoInfo = await client.GetVideoAsync(VideoId); // Print metadata Console.WriteLine($"Id: {videoInfo.Id} | Title: {videoInfo.Title} | Author: {videoInfo.Author.Title}"); #endif try { //var streamInfo = videoInfo.MixedStreams // .OrderBy(s => s.VideoEncoding == VideoEncoding.Vp8) // .ThenBy(s => s.VideoQuality == VideoQuality.High720).Last(); //youtubePlayer.LoadHtml( // $"<html><body scroll=\"no\" style=\"overflow: hidden\"><iframe id = \"youtubePlayer\" src=\"http://youtube.com/embed/{videoInfo.Id}?autoplay=1&controls=0&disablekb=1&enablejsapi=1&rel=0&showinfo=0&showsearch=0\" width=\"480\" height=\"270\" frameborder=\"0\" allowfullscreen=\"\" Style =\"pointer-events:none;\"></iframe>", // "Music Player"); youtubePlayer.LoadHtml($"<html>\r\n\r\n<body scroll=\"no\" style=\"overflow: hidden\">\r\n <div id=\"youtubePlayer\"></div>\r\n <script>\r\n var tag = document.createElement(\'script\');\r\n tag.src = \"https://www.youtube.com/iframe_api\";\r\n var firstScriptTag = document.getElementsByTagName(\'script\')[0];\r\n firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);\r\n var youtubePlayer;\r\n\r\n var playBackEnded;\r\n\r\n function onYouTubeIframeAPIReady() {{\r\n youtubePlayer = new YT.Player(\'youtubePlayer\', {{\r\n height: \'270\'\r\n , width: \'480\'\r\n , videoId: \'{VideoId}\'\r\n , playerVars: {{\r\n controls: \'0\'\r\n , disablekb: \'1\'\r\n , autoplay: \'1\'\r\n , showinfo: \'0\'\r\n , modestbranding: \'1\'\r\n , rel: \'0\'\r\n , showsearch: \'0\'\r\n }}, events: {{\r\n \'onStateChange\': onPlayerStateChange\r\n }}\r\n }});\r\n }}\r\n function onPlayerStateChange(event){{\r\n if( event.data == YT.PlayerState.ENDED) playBackEnded = true; else playBackEnded = false;\r\n }} </script>\r\n</body>\r\n\r\n</html>", "http://youtube.com"); Console.WriteLine("Player loaded? " + youtubePlayer.IsLoaded); } catch { // var streamInfo = videoInfo.MixedStreams // .OrderBy(s => s.VideoEncoding == VideoEncoding.Vp8) // .ThenBy(s => s.VideoQuality == VideoQuality.Medium480).Last(); youtubePlayer.LoadHtml($"<html>\r\n\r\n<body scroll=\"no\" style=\"overflow: hidden\">\r\n <div id=\"youtubePlayer\"></div>\r\n <script>\r\n var tag = document.createElement(\'script\');\r\n tag.src = \"https://www.youtube.com/iframe_api\";\r\n var firstScriptTag = document.getElementsByTagName(\'script\')[0];\r\n firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);\r\n var youtubePlayer;\r\n\r\n var playBackEnded;\r\n\r\n function onYouTubeIframeAPIReady() {{\r\n youtubePlayer = new YT.Player(\'youtubePlayer\', {{\r\n height: \'270\'\r\n , width: \'480\'\r\n , videoId: \'{VideoId}\'\r\n , playerVars: {{\r\n controls: \'0\'\r\n , disablekb: \'1\'\r\n , autoplay: \'1\'\r\n , showinfo: \'0\'\r\n , modestbranding: \'1\'\r\n , rel: \'0\'\r\n , showsearch: \'0\'\r\n }}, events: {{\r\n \'onStateChange\': onPlayerStateChange\r\n }}\r\n }});\r\n }}\r\n function onPlayerStateChange(event){{\r\n if( event.data == YT.PlayerState.ENDED) playBackEnded = true; else playBackEnded = false;\r\n }} </script>\r\n</body>\r\n\r\n</html>", "http://youtube.com"); Console.WriteLine("Player loaded? " + youtubePlayer.IsLoaded); } //Console.WriteLine("Can execute JS: "+ youtubePlayer.CanExecuteJavascriptInMainFrame); #if OFFLINE_IMPLEMENTED streamInfo = videoInfo.MixedStreams .OrderBy(s => s.VideoEncoding == YoutubeExplode.Models.mediaStreams.VideoEncoding.H264) .Last(); // Compose file name, based on metadata string fileExtension = streamInfo.Container.GetFileExtension(); string saveName = $"{videoInfo.Title}.{fileExtension}"; // Remove illegal characters from file name saveName = FilePaths.RemoveIllegalPathCharacters(saveName); // Download video Console.WriteLine($"Downloading to [{saveName}]..."); string savePath = Path.Combine(FilePaths.SaveLocation(), saveName); await client.DownloadmediaStreamAsync(streamInfo, savePath); //File.WriteAllBytes(savePath, bytes); SongTitle = savePath; Console.WriteLine("Done downloading " + SongTitle); return(savePath); #endif return(VideoId); }
private void DownloadFile() { if (radioAudio.Checked) { try { setTextProgress("Iniciando Download..."); IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(txtLink.Text); VideoInfo video = videoInfos .Where(info => info.CanExtractAudio) .OrderByDescending(info => info.AudioBitrate) .First(); if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } setTextMediaInfo(video.Title); setTextProgress("Baixando " + video.Title); string outputTitle = video.Title; foreach (char c in System.IO.Path.GetInvalidFileNameChars()) { outputTitle = outputTitle.Replace(c, '_'); } var audioDownloader = new AudioDownloader(video, Path.Combine("C:/Downloads", outputTitle + video.AudioExtension)); audioDownloader.DownloadProgressChanged += (sender, args) => this.Invoke((MethodInvoker) delegate { progressFile.Value = (int)(args.ProgressPercentage * 0.85); lblprogress.Text = Math.Round(args.ProgressPercentage * 0.85, 2).ToString() + "%"; }); audioDownloader.AudioExtractionProgressChanged += (sender, args) => this.Invoke((MethodInvoker) delegate { progressFile.Value = (int)(85 + args.ProgressPercentage * 0.15); lblprogress.Text = Math.Round(85 + args.ProgressPercentage * 0.15, 2).ToString() + "%"; }); audioDownloader.DownloadFinished += (sender, args) => this.Invoke((MethodInvoker) delegate { progressFile.Value = 0; lblprogress.Text = ("Download Finalizado!"); }); audioDownloader.Execute(); } catch (Exception e) { this.Invoke((MethodInvoker) delegate { MetroMessageBox.Show(this, "Falha ao Baixar o audio " + e.Message); }); } } else { try { setTextProgress("Iniciando Download..."); IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(txtLink.Text); VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 360); if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } setTextProgress("Baixando " + video.Title); setTextMediaInfo(video.Title); string outputTitle = video.Title; foreach (char c in System.IO.Path.GetInvalidFileNameChars()) { outputTitle = outputTitle.Replace(c, '_'); } var videoDownloader = new VideoDownloader(video, Path.Combine("C:/Downloads", outputTitle + video.VideoExtension)); videoDownloader.DownloadProgressChanged += (sender2, args) => this.Invoke((MethodInvoker) delegate { progressFile.Value = (int)(Math.Round(args.ProgressPercentage, 2)); lblprogress.Text = Math.Round(args.ProgressPercentage, 2) + "%"; }); videoDownloader.DownloadFinished += (sender2, args) => this.Invoke((MethodInvoker) delegate { progressFile.Value = 0; lblprogress.Text = ("Download Finalizado!"); }); videoDownloader.Execute(); } catch (Exception e) { this.Invoke((MethodInvoker) delegate { MetroMessageBox.Show(this, "Falha ao Baixar o vídeo " + e.Message); }); } } }
private void Downloader (YouTubeVideo video, MainProgramElements mainWindow, bool isAudio) { string temporaryDownloadPath = Path.Combine(this.UserSettings.TemporarySaveLocation, video.FullName); string movingPath = Path.Combine(this.UserSettings.MainSaveLocation, video.FullName); if (this.UserSettings.ValidationLocations.All(path => !File.Exists(Path.Combine(path, video.FullName)) && !File.Exists(movingPath)) { if(isAudio) { var audioDownloader = new AudioDownloader (video, temporaryDownloadPath);; audioDownloader.AudioExtractionProgressChanged += (sender, args) => mainWindow.CurrentDownloadProgress = (int)(85 + args.ProgressPercentage * 0.15); audioDownloader.Execute(); } else { var videoDownloader = new VideoDownloader (video, temporaryDownloadPath); videoDownloader.DownloadProgressChanged += ((sender, args) => mainWindow.CurrentDownloadProgress = (int)args.ProgressPercentage); videoDownloader.Execute(); } if (!temporaryDownloadPath.Equals(movingPath, StringComparison.OrdinalIgnoreCase)) File.Move(temporaryDownloadPath, movingPath); } else { throw new DownloadCanceledException(string.Format(CultureInfo.CurrentCulture, "The download of #{0} '{1}({2})' has been canceled because it already existed.", videoToUse.Position, RemoveIllegalPathCharacters(video.Title).Truncate(10), videoToUse.Location.Truncate(100))); } }
private void DownloadAudio(IEnumerable <VideoInfo> videoInfos) { try { VideoInfo video = videoInfos .First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 0); if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } try { var videoDownloader = new VideoDownloader(video, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), RemoveIllegalPathCharacters(video.Title) + ".mp3")); S = RemoveIllegalPathCharacters(video.Title) + ".mp3"; //video.VideoExtension; double x = Convert.ToDouble(videoDownloader.BytesToDownload); videoDownloader.DownloadProgressChanged += (sender, args) => bw.ReportProgress(Convert.ToInt32(args.ProgressPercentage)); // label3.Text = videoDownloader.BytesToDownload.ToString(); videoDownloader.Execute(); MessageBox.Show("Audio Download Completed on your Desktop"); Application.Restart(); bw.ReportProgress(0); } catch (Exception exe) { MessageBox.Show("An error has occured while downloading this audio.This might be because of problems in your network connection"); Application.Restart(); } } catch (Exception ex) { MessageBox.Show(" Error Occured"); Application.Restart(); } /* * try * { * VideoInfo video = videoInfos * .Where(info => info.CanExtractAudio) * .OrderByDescending(info => info.AudioBitrate) * .First(); * * * if (video.RequiresDecryption) * { * DownloadUrlResolver.DecryptDownloadUrl(video); * } * * var audioDownloader = new AudioDownloader(video, * Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), * RemoveIllegalPathCharacters(video.Title) + video.AudioExtension)); * S = RemoveIllegalPathCharacters(video.Title) + video.AudioExtension; * // label3.Text = S; * * audioDownloader.DownloadProgressChanged += (sender, args) => bw.ReportProgress(Convert.ToInt32(args.ProgressPercentage)); * audioDownloader.Execute(); * * MessageBox.Show("Audio Download Completed on your Desktop"); * Application.Restart(); * bw.ReportProgress(0); * } * catch(Exception ex) * { * // * * MessageBox.Show("There is error downloading the audio"); * Application.Restart(); * * } */ }
private void DownloadYoutubeLink(YoutubeFile youtubeFile, User user) { Task.Run(() => { VideoInfo video = null; try { IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(youtubeFile.Url); video = videoInfos.First(info => info.VideoType == VideoType.Mp4); } catch (Exception e) { Console.WriteLine(e.ToString()); user.YoutubeLinks.Remove(youtubeFile); return; } if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/Downloaded")) { Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/Downloaded"); } var fileName = NormalizeFileName(video.Title); var videoDownloader = new VideoDownloader(video, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/Downloaded", fileName + video.AudioExtension)); try { videoDownloader.Execute(); } catch (Exception e) { Console.WriteLine(e.ToString()); user.YoutubeLinks.Remove(youtubeFile); return; } // Convert to mp4 to mp3 // ------------------- var inputFile = new MediaFile { Filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/Downloaded", fileName + video.AudioExtension) }; var outputFile = new MediaFile { Filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/Downloaded", fileName + ".mp3") }; using (var engine = new Engine()) { engine.GetMetadata(inputFile); engine.Convert(inputFile, outputFile); } // ------------------- youtubeFile.Name = video.Title; youtubeFile.Duration = inputFile.Metadata.Duration.TotalSeconds; youtubeFile.Downloaded = true; youtubeFile.Path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/Downloaded", fileName + ".mp3"); File.Delete(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/Downloaded", fileName + video.AudioExtension)); this.OnYoutubeFileDownloadFinish(); }); }
private async Task AccessPlaylist() { UserCredential credential; using (var stream = new FileStream(@"C:\client_id.json", FileMode.Open, FileAccess.Read)) { credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, // This OAuth 2.0 access scope allows for read-only access to the authenticated // user's account, but not other types of account access. new[] { YouTubeService.Scope.YoutubeReadonly }, "psangat", CancellationToken.None, new FileDataStore(this.GetType().ToString()) ); } var youtubeService = new YouTubeService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = this.GetType().ToString() }); var playlists = youtubeService.Playlists.List("snippet"); playlists.PageToken = ""; playlists.MaxResults = 50; playlists.Mine = true; PlaylistListResponse presponse = await playlists.ExecuteAsync(); foreach (var currentPlayList in presponse.Items) { if (currentPlayList.Snippet.Title.Equals("Songs")) { PlaylistItemsResource.ListRequest listRequest = youtubeService.PlaylistItems.List("contentDetails"); listRequest.MaxResults = 50; listRequest.PlaylistId = currentPlayList.Id; listRequest.PageToken = playlists.PageToken; var response = await listRequest.ExecuteAsync(); var index = 1; foreach (var playlistItem in response.Items) { VideosResource.ListRequest videoR = youtubeService.Videos.List("snippet, contentDetails, status"); videoR.Id = playlistItem.ContentDetails.VideoId; var responseV = await videoR.ExecuteAsync(); if (responseV.Items.Count > 0) { string link = String.Format("https://www.youtube.com/watch?v={0}&list={1}&index={2}", videoR.Id, currentPlayList.Id, index); IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link); try { VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 0 && !String.IsNullOrEmpty(info.Title)); Console.WriteLine("Downloading {0}", video.Title); if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } using (var progress = new ProgressBar()) { for (int i = 0; i <= 100; i++) { progress.Report((double)i / 100); Thread.Sleep(20); } } var audioDownloader = new VideoDownloader(video, Path.Combine(@"C:\Users\prsangat\Desktop\Songs", video.Title + ".mp3")); using (var progress = new ProgressBar()) { audioDownloader.DownloadProgressChanged += (sender, args) => progress.Report(args.ProgressPercentage); } //audioDownloader.DownloadProgressChanged += (sender, args) => progre//Console.Write( "\r{0}% ", Math.Round(args.ProgressPercentage)); audioDownloader.Execute(); Console.WriteLine("Download Complete."); } catch (Exception ex) { Console.WriteLine(); Console.WriteLine(ex.ToString()); Console.WriteLine(); // throw; } index++; } } playlists.PageToken = response.NextPageToken; } } }
/// <summary> /// Download the video and perform verification /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void downloadButton_Click(object sender, EventArgs e) { try { //Temporary variable to store the filename string fileName = System.IO.Path.GetFileName(saveLocationTextBox.Text); //Loop and replace invalid characters in filename foreach (char c in System.IO.Path.GetInvalidFileNameChars()) { fileName = fileName.Replace(c, '_'); } //Check if the file already exists in the selected directory if (File.Exists(System.IO.Path.GetDirectoryName(saveLocationTextBox.Text) + "\\" + fileName)) { //Message to override file DialogResult dialogResult = MessageBox.Show("A file already exists with that name, would you like to overwrite the file?", "File Already Exists", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (dialogResult == DialogResult.Yes) { //Change cursor to wait cursor System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor; //Show message to user that is downloading statusLabel.ForeColor = System.Drawing.Color.Red; statusLabel.Text = "Downloading Video...\nPlease wait"; this.Refresh(); //Select the video user selected VideoInfo video = videoInfos[videoQualityComboBox.SelectedIndex]; // Decipher the video if it has a decrypted signature if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } // Initiate a new VideoDownloader object, passing the VideoInfo object and save path VideoDownloader videoDownloader = new VideoDownloader(video, System.IO.Path.GetDirectoryName(saveLocationTextBox.Text) + "\\" + fileName); // Execute the video downloader videoDownloader.Execute(); //Show message download completed statusLabel.ForeColor = System.Drawing.Color.Green; statusLabel.Text = " Download Completed!"; //Change cursor back System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; //Clear ComboBox videoQualityComboBox.Items.Clear(); //Clear Array of videos if (videoInfos != null) { Array.Clear(videoInfos, 0, videoInfos.Length); } //Clear save location saveLocationTextBox.Text = String.Empty; } } else { //Change cursor to wait cursor System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor; //Show message to user that is downloading statusLabel.ForeColor = System.Drawing.Color.Red; statusLabel.Text = "Downloading Video...\nPlease wait"; this.Refresh(); //Select the video user selected VideoInfo video = videoInfos[videoQualityComboBox.SelectedIndex]; // Decipher the video if it has a decrypted signature if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } // Initiate a new VideoDownloader object, passing the VideoInfo object and save path VideoDownloader videoDownloader = new VideoDownloader(video, System.IO.Path.GetDirectoryName(saveLocationTextBox.Text) + "\\" + fileName); // Execute the video downloader videoDownloader.Execute(); //Show message download completed statusLabel.ForeColor = System.Drawing.Color.Green; statusLabel.Text = " Download Completed!"; //Change cursor back System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; MessageBox.Show("Video downloaded successfully", "Download Complete", MessageBoxButtons.OK, MessageBoxIcon.Information); //Clear ComboBox videoQualityComboBox.Items.Clear(); //Clear Array of videos if (videoInfos != null) { Array.Clear(videoInfos, 0, videoInfos.Length); } //Clear save location saveLocationTextBox.Text = String.Empty; } } catch (ArgumentException) { System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; statusLabel.Text = String.Empty; MessageBox.Show("Please provide a valid path to save the vide. Do not include special characters in filename", "Download Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (Exception) { System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; statusLabel.Text = String.Empty; MessageBox.Show("Therer was a problem, your video couldn't be downloaded. Please try again", "Download Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void DownloadMp3(IEnumerable <VideoInfo> videoInfos, string destinationDirectory) { int latestReportedProgress = 0; /* * Select the .mp4 video with highest resolution */ VideoInfo video = videoInfos .Where(info => info.VideoType == VideoType.Mp4 && info.AudioBitrate > 0) .OrderByDescending(info => info.AudioBitrate) .First(); /* * If the video has a decrypted signature, decipher it */ if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } /* * Create the video downloader. * The first argument is the video to download. * The second argument is the path to save the video file. */ var mp4file = RemoveIllegalPathCharacters(video.Title + video.VideoExtension); var mp3file = RemoveIllegalPathCharacters(video.Title + ".mp3"); var videoPath = Path.Combine(destinationDirectory, mp4file); var audioPath = Path.Combine(destinationDirectory, mp3file); if (!File.Exists(videoPath)) { Console.Write("Download: -"); var videoDownloader = new VideoDownloader(video, videoPath); // Register the ProgressChanged event and print the current progress videoDownloader.DownloadProgressChanged += (sender, args) => { if (args.ProgressPercentage > (latestReportedProgress + 10)) { Console.Write("-"); latestReportedProgress += 10; } if (args.ProgressPercentage == 100.0) { Console.WriteLine(); } }; /* * Execute the video downloader. * For GUI applications note, that this method runs synchronously. */ videoDownloader.Execute(); } if (!File.Exists(audioPath)) { Console.WriteLine("Convert: ----------"); string arg = String.Format(@"-i ""{0}"" ""{1}""", mp4file, mp3file); Process proc = new Process(); proc.StartInfo.WorkingDirectory = destinationDirectory; proc.StartInfo.FileName = @"ffmpeg"; proc.StartInfo.Arguments = arg; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.UseShellExecute = false; proc.Start(); proc.WaitForExit(); } if (File.Exists(videoPath) && File.Exists(audioPath)) { Console.WriteLine("Delete video"); File.Delete(videoPath); } }
public void downloadYoutube() { //채워진 url을 이용하여 다운로드 시작 for (int j = 0; j < list_downUrls.Items.Count; j++) { list_downUrls.Invoke(new Action(delegate() { list_downUrls.SelectedIndex = j; })); IEnumerable <VideoInfo> videoinfos = DownloadUrlResolver.GetDownloadUrls(list_downUrls.Items[j].ToString()); if (videoinfos != null) { int displayP = 0; cmb_size.Invoke(new Action(delegate() { displayP = int.Parse(cmb_size.SelectedItem.ToString()); })); //VideoInfo video = videoinfos.First(x => x.VideoType == VideoType.Mp4 && x.Resolution == 720); VideoInfo video = checkP(videoinfos, displayP); if (video != null) { if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } string selectItems = string.Empty; list_Keywords.Invoke(new Action(delegate { selectItems = list_Keywords.SelectedItem.ToString(); })); //키워드 폴더를 만들어 분류하여 저장함 string createfolderPath = Path.Combine(txt_filePath.Text, selectItems); if (!Directory.Exists(createfolderPath)) { Directory.CreateDirectory(createfolderPath); } string videotitle = video.Title.Replace(@"\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace("\"", "").Replace("<", "").Replace(">", "").Replace("|", ""); string filepath = Path.Combine(createfolderPath, videotitle + video.VideoExtension); //기존 존재하는 파일이 있다면 파일명 뒤에 _1을 붙임 //if (File.Exists(filepath)) //{ // filepath = Path.Combine(createfolderPath, videotitle + "_1" + video.VideoExtension); //} var videoDownloader = new VideoDownloader(video, filepath); try { videoDownloader.Execute(); } catch { string error = string.Empty; list_downUrls.Invoke(new Action(delegate { error = list_downUrls.SelectedItem + "\r\n"; })); txt_errorUrls.Invoke(new Action(delegate { txt_errorUrls.Text += error; })); } //파일이름과 링크를 텍스트파일에 저장해야한다.(VideoDB 수집문제) writeLog(videotitle + " : " + list_downUrls.Items[j].ToString()); } else { string error = string.Empty; list_downUrls.Invoke(new Action(delegate { error = list_downUrls.SelectedItem + "\r\n"; })); txt_errorUrls.Invoke(new Action(delegate { txt_errorUrls.Text += error; })); //txt_errorUrls.Text += list_downUrls.SelectedItem + "\r\n"; } } else { string error = string.Empty; list_downUrls.Invoke(new Action(delegate { error = list_downUrls.SelectedItem + "\r\n"; })); txt_errorUrls.Invoke(new Action(delegate { txt_errorUrls.Text += error; })); } } //cnd.Signal(); }
void DownloadVideo(VideoInfo videoInfo) { try { if (videoInfo.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(videoInfo); } var fullFileName = $"{Guid.NewGuid()}{videoInfo.VideoExtension}"; var videoDownloader = new VideoDownloader(videoInfo, Path.Combine(ApplicationInfo.DataDir, fullFileName)); var video = new Video(videoInfo.Title, videoDownloader.SavePath); Storage.Instance.SaveVideo(video); var downloadView = new DownloadItemView(this, videoDownloader, video); downloadView.DownloadFinished += (sender, e) => { RunOnUiThread(() => { _downloadsView.RemoveView(sender as View); }); if (e.TrySetFinishedStatus()) { Storage.Instance.SaveVideos(); } }; downloadView.ProgressChanged += (sender, e) => { SetFreeSize(); if (e.TrySetInProgressStatus()) { Storage.Instance.SaveVideos(); } }; _downloadsView.AddView(downloadView); var thread = new Thread(() => { try { videoDownloader.Execute(); }catch (Exception ex) { Tracker.TrackVideoDownloadingFailed(); RunOnUiThread(() => { Toast.MakeText(this, ex.Message, ToastLength.Short).Show(); }); } }); thread.Start(); }catch (Exception ex) { Tracker.TrackStartDownloadVideoFailed(); Toast.MakeText(this, ex.Message, ToastLength.Short).Show(); } }