Example #1
0
        public static async void SendMusic2TG(object mp3Class)
        {
            MP3    mp3classFile = (MP3)mp3Class;
            string url          = mp3classFile.Link;
            string file         = mp3classFile.Name;
            string msg          = mp3classFile.Message;
            string author       = mp3classFile.Artists;
            string title        = mp3classFile.Title;
            Uri    thumb        = mp3classFile.Thumb;

            try
            {
                AudioDownloader.DownloadMP3FromUrl(url, file);

                long length = new System.IO.FileInfo(file).Length;//in bytes

                double fifty_megabytes = 5e+7;

                if (length < fifty_megabytes) //Проверка на размер для телеги
                {
                    await TelegramMusic.SendAudioFromFileAsync(file, msg, author, title, thumb);
                }
                else
                {
                    Console.WriteLine("Слишком большой файл >50MB");
                }
            }
            catch (Exception ex) { Logging.ErrorLogging(ex); Logging.ReadError(); }
        }
Example #2
0
        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            var episode = _album.Episodes[position];

            View iconAndTitleView;

            if (AndroidAudioDownloader.ViewsDownloadInProgressByAudioId.ContainsKey(episode.RemoteUrl))
            {
                iconAndTitleView = AndroidAudioDownloader.ViewsDownloadInProgressByAudioId [episode.RemoteUrl];
            }
            else
            {
                iconAndTitleView = base.GetView(position, convertView, parent);
                iconAndTitleView.SetNarratorsAndAuthors(episode.Authors == null ? (IManMadeItem)episode : _album);

                var downloadProgressBar = iconAndTitleView.FindViewById <ProgressBar> (Resource.Id.DownloadProgress);
                downloadProgressBar.Progress =
                    AudioDownloader.HasLocalFile(episode.RemoteUrl, episode.FileSize) ? downloadProgressBar.Max : 0;
            }

            if (episode == DrunkAudibleApplication.Self.CurrentEpisode)
            {
                var isPlayingIndicator = iconAndTitleView.FindViewById <TextView> (Resource.Id.IsPlayingIndicator);
                IconProvider.ConvertTextViewToIcon(Context.Assets, isPlayingIndicator);
                isPlayingIndicator.Visibility = ViewStates.Visible;
            }

            return(iconAndTitleView);
        }
Example #3
0
        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)));
            }
        }
Example #4
0
        private static void DownloadAudio(IEnumerable <VideoInfo> videoInfos)
        {
            /*
             * We want the first extractable video with the highest audio quality.
             */
            VideoInfo video = videoInfos
                              .Where(info => info.CanExtractAudio)
                              .OrderByDescending(info => info.AudioBitrate)
                              .First();

            /*
             * Create the audio downloader.
             * The first argument is the video where the audio should be extracted from.
             * The second argument is the path to save the audio file.
             */
            var audioDownloader = new AudioDownloader(video, Path.Combine("D:/Downloads", video.Title + video.AudioExtension));

            // Register the ProgressChanged event and print the current progress
            audioDownloader.ProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage);

            /*
             * Execute the audio downloader.
             * For GUI applications note, that this method runs synchronously.
             */
            audioDownloader.Execute();
        }
Example #5
0
        private static void DownloadAudio(VideoInfo video, string pth)
        {
            /*
             * We want the first extractable video with the highest audio quality.
             */

            /*
             * If the video has a decrypted signature, decipher it
             */
            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }

            /*
             * Create the audio downloader.
             * The first argument is the video where the audio should be extracted from.
             * The second argument is the path to save the audio file.
             */

            var audioDownloader = new AudioDownloader(video, pth);

            // Register the progress events. We treat the download progress as 85% of the progress
            // and the extraction progress only as 15% of the progress, because the download will
            // take much longer than the audio extraction.
            audioDownloader.DownloadProgressChanged        += (sender, args) => Console.WriteLine(args.ProgressPercentage * 0.85);
            audioDownloader.AudioExtractionProgressChanged += (sender, args) => Console.WriteLine(85 + args.ProgressPercentage * 0.15);

            /*
             * Execute the audio downloader.
             * For GUI applications note, that this method runs synchronously.
             */
            audioDownloader.Execute();
        }
Example #6
0
        static void DownloadMP3(string link, string downloadDir)
        {
            Directory.CreateDirectory(downloadDir);
            IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link);

            // Extracting stream with highest quality
            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(downloadDir, RemoveIllegalPathCharacters(video.Title) + video.AudioExtension));
            int ticks           = 0;

            audioDownloader.DownloadProgressChanged += (sender, argss) =>
            {
                ticks++;

                if (ticks > 1000)
                {
                    Console.Write("#");
                    ticks -= 1000;
                }
            };
            audioDownloader.DownloadFinished += (sender, argss) =>
            {
                Console.WriteLine("\nFinished download " + video.Title + video.AudioExtension);
            };

            audioDownloader.Execute();
        }
Example #7
0
        private static void bw_downloadAudio(object send, DoWorkEventArgs e)
        {
            isVideo_ = false;
            isAudio_ = true;
            BackgroundWorker worker = send as BackgroundWorker;

            if (dir_ != " ")
            {
                //Parameter for video type
                IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(url_);
                VideoInfo video = videoInfos.Where(info => info.CanExtractAudio).OrderByDescending(info => info.AudioBitrate).First();

                if (video.RequiresDecryption)
                {
                    DownloadUrlResolver.DecryptDownloadUrl(video);
                }
                audioDownloader_ = new AudioDownloader(video, dir_);
                audioDownloader_.AudioExtractionProgressChanged += (sender, args) => progBar_.Invoke((Action)(() => { worker.ReportProgress((int)(85 + args.ProgressPercentage * 0.15)); }));
                try
                {
                    audioDownloader_.Execute();
                }
                catch (WebException we)
                {
                    MessageBox.Show("The video returned an error, please try again later",
                                    we.Response.ToString(),
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Example #8
0
        private void DownloadMp3(LinkInfo link, string downloadDir)
        {
            Directory.CreateDirectory(downloadDir);
            IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link.Link);

            // Extracting stream with highest quality
            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(downloadDir, RemoveIllegalPathCharacters(video.Title) + video.AudioExtension));

            audioDownloader.DownloadProgressChanged += (sender, argss) =>
            {
                downloader.ReportProgress((int)argss.ProgressPercentage);
            };
            audioDownloader.DownloadFinished += (sender, argss) =>
            {
            };

            audioDownloader.Execute();
        }
Example #9
0
        public override void LoadToCache()
        {
            this.IsCaching = true;

            string tempPath = Path.GetTempFileName();

            IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(this.OriginalPath);

            VideoInfo video = videoInfos
                              .Where(info => info.CanExtractAudio)
                              .First(info =>
                                     info.VideoFormat == VideoFormat.FlashMp3HighQuality ||
                                     info.VideoFormat == VideoFormat.FlashMp3LowQuality);

            var downloader = new AudioDownloader(video, tempPath);

            downloader.ProgressChanged += (sender, args) =>
            {
                this.CachingProgress = (int)args.ProgressPercentage;
            };

            downloader.Execute();
            this.StreamingPath = tempPath;

            this.IsCached = true;
        }
Example #10
0
        private static void DownloadAudio(IEnumerable <VideoInfo> videoInfos)
        {
            /*
             * We want the first flash (only flash audio extraction is currently supported)
             * video with the highest audio quality.
             * See the VideoFormat enum for more info about the quality.
             */
            VideoInfo video = videoInfos
                              .Where(info => info.CanExtractAudio)
                              .First(info =>
                                     info.VideoFormat == VideoFormat.FlashAacHighQuality ||
                                     info.VideoFormat == VideoFormat.FlashAacLowQuality ||
                                     info.VideoFormat == VideoFormat.FlashMp3HighQuality ||
                                     info.VideoFormat == VideoFormat.FlashMp3LowQuality);

            /*
             * Create the audio downloader.
             * The first argument is the video where the audio should be extracted from.
             * The second argument is the path to save the audio file.
             */
            var audioDownloader = new AudioDownloader(video, Path.Combine("D:/Downloads", video.Title + video.AudioExtension));

            // Register the ProgressChanged event and print the current progress
            audioDownloader.ProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage);

            /*
             * Execute the audio downloader.
             * For GUI applications note, that this method runs synchronously.
             */
            audioDownloader.Execute();
        }
Example #11
0
        public void Download(string filename)
        {
            var video = GetVideoInfo();

            /*
             * If the video has a decrypted signature, decipher it
             */
            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }

            /*
             * Create the audio downloader.
             * The first argument is the video where the audio should be extracted from.
             * The second argument is the path to save the audio file.
             */
            var audioDownloader = new AudioDownloader(video, filename);

            // Register the progress events. We treat the download progress as 85% of the progress and the extraction progress only as 15% of the progress,
            // because the download will take much longer than the audio extraction.
            audioDownloader.DownloadProgressChanged        += (sender, args) => RaiseProgressEvent(args.ProgressPercentage * 0.85);
            audioDownloader.AudioExtractionProgressChanged += (sender, args) => RaiseProgressEvent(85 + args.ProgressPercentage * 0.15);
            audioDownloader.DownloadFinished += (sender, args) => RaiseProgressEvent(101.0);

            /*
             * Execute the audio downloader.
             * For GUI applications note, that this method runs synchronously.
             */
            audioDownloader.Execute();
        }
Example #12
0
 public ProcessPlaylistItemJob(
     IPlaylistRepository playlistRepository,
     IAudioUploadProcessService uploadService,
     IOptions <AppSettings> appSettings,
     IPodcastRepository podcastRepository,
     IOptions <ImageFileStorageSettings> imageStorageSettings,
     IOptions <StorageSettings> storageSettings,
     IOptions <HelpersSettings> helpersSettings,
     IUnitOfWork unitOfWork,
     IUrlProcessService processor,
     EntryPreProcessor preProcessor,
     AudioDownloader audioDownloader,
     ILogger <ProcessPlaylistItemJob> logger) : base(logger)
 {
     _unitOfWork           = unitOfWork;
     _processor            = processor;
     _preProcessor         = preProcessor;
     _playlistRepository   = playlistRepository;
     _uploadService        = uploadService;
     _appSettings          = appSettings.Value;
     _podcastRepository    = podcastRepository;
     _storageSettings      = storageSettings.Value;
     _imageStorageSettings = imageStorageSettings.Value;
     _helpersSettings      = helpersSettings.Value;
     _audioDownloader      = audioDownloader;
 }
Example #13
0
        private static void DownloadAudio(IEnumerable <VideoInfo> videoInfos)
        {
            /*
             * We want the first extractable video with the highest audio quality.
             */
            VideoInfo video = videoInfos
                              .Where(info => info.CanExtractAudio)
                              .OrderByDescending(info => info.AudioBitrate)
                              .First();

            /*
             * Create the audio downloader.
             * The first argument is the video where the audio should be extracted from.
             * The second argument is the path to save the audio file.
             */

            var audioDownloader = new AudioDownloader(video,
                                                      Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), video.Title + video.AudioExtension));

            // Register the progress events. We treat the download progress as 85% of the progress and the extraction progress only as 15% of the progress,
            // because the download will take much longer than the audio extraction.
            audioDownloader.DownloadProgressChanged        += (sender, args) => Console.WriteLine(args.ProgressPercentage * 0.85);
            audioDownloader.AudioExtractionProgressChanged += (sender, args) => Console.WriteLine(85 + args.ProgressPercentage * 0.15);

            /*
             * Execute the audio downloader.
             * For GUI applications note, that this method runs synchronously.
             */
            audioDownloader.Execute();
        }
Example #14
0
        static void DownloadMusic(string videoID)
        {
            IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls("https://www.youtube.com/watch?v=" + videoID);

            VideoInfo video = videoInfos.Where(info => info.AudioType == AudioType.Mp3 && info.CanExtractAudio).OrderByDescending(info => info.AudioBitrate).First();

            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }
            var audioDownload = new AudioDownloader(video, Path.Combine("Downloads/", RemoveIllegalPathCharacters(video.Title) + video.AudioExtension));

            audioDownload.DownloadStarted += (sender, args) =>
            {
                Console.WriteLine("Downloading " + video.Title + video.AudioExtension);
            };
            int ticks = 0;

            audioDownload.DownloadProgressChanged += (sender, args) =>
            {
                ticks++;
                if (ticks > 300)
                {
                    ticks -= 300;
                    Console.Write("|");
                }
            };
            audioDownload.DownloadFinished += (sender, args) =>
            {
                Console.WriteLine("Finished " + video.Title + video.AudioExtension);
            };
            audioDownload.Execute();
        }
Example #15
0
        async void OnAlbumItemClicked(object sender, AdapterView.ItemClickEventArgs e)
        {
            var selectedEpisode = _album.Episodes [e.Position];

            if (AndroidAudioDownloader.ViewsDownloadInProgressByAudioId.ContainsKey(selectedEpisode.RemoteUrl))
            {
                return;
            }

            if (AudioDownloader.HasLocalFile(selectedEpisode.RemoteUrl, selectedEpisode.FileSize))
            {
                var resultIntent = new Intent();
                ExtraUtils.PutEpisode(resultIntent, selectedEpisode.Id);
                ExtraUtils.PutAlbum(resultIntent, _album.Id);
                ExtraUtils.PutSelectedTab(resultIntent, (int)MainActivity.TabTitle.Player);
                SetResult(Result.Ok, resultIntent);

                StartService(PlayerService.CreateIntent(
                                 this,
                                 PlayerService.ACTION_PLAY,
                                 _album.Id,
                                 selectedEpisode.Id
                                 ));

                Finish();
            }
            else
            {
                await AndroidAudioDownloader.StartDownloadAsync(e.Position, selectedEpisode.RemoteUrl, ListView);
            }
        }
Example #16
0
//	HashSet<string> activeAudioDownloads = new HashSet<string>();
//	HashSet<string> activeAudioDownloads = new HashSet<string>();

    protected override void Init()
    {
        Debug.Log("[GameManager] init");
        Persist         = true;
        imageDownloader = new ImageDownloader(textureCache, this);
        audioDownloader = new AudioDownloader(audioCache, this);
    }
        public static void DownloadAudio(IEnumerable <VideoInfo> videoInfos)
        {
            try
            {
                VideoInfo video = videoInfos.Where(info => info.CanExtractAudio).OrderByDescending(info => info.AudioBitrate).First();

                if (video.RequiresDecryption)
                {
                    DownloadUrlResolver.DecryptDownloadUrl(video);
                }

                string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\YouTubeAudios";

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                var savePath = Path.Combine(path, YouTubeHelpers.RemoveIllegalPathCharacters(video.Title) + video.AudioExtension);

                var audioDownloader = new AudioDownloader(video, savePath);

                audioDownloader.DownloadProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage * 0.85);

                audioDownloader.AudioExtractionProgressChanged += (sender, args) => Console.WriteLine(85 + args.ProgressPercentage * 0.15);

                audioDownloader.Execute();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #18
0
        public DownloadAudioItem(DownloadType type, string name, AudioDownloader downloader)
        {
            DType      = type;
            ItemName   = name;
            Downloader = downloader;

            StartDownload();
        }
 public UrlProcessController(IHttpContextAccessor contextAccessor, UserManager <ApplicationUser> userManager,
                             ILogger <UrlProcessController> logger, IUrlProcessService processService,
                             AudioDownloader downloader) :
     base(contextAccessor, userManager, logger)
 {
     this._processService = processService;
     this._downloader     = downloader;
 }
        public void EventListeningTest()
        {
            var yc = new YoutubeContext(Url, true) {BaseDirectory = new DirectoryInfo(Path.GetTempPath())};
            var ad = new AudioDownloader(yc);

            var sb = new StringBuilder();

            yc.DownloadFailed += (sender, args) => {
                Debug.WriteLine(args.Subject + "\n" + args.Exception);
                sb.AppendLine(args.Subject + "\n" + args.Exception);
            };

            yc.ProgresStateChanged += (sender, args) => {
                if (args.UIHandled || args.Stage != YoutubeStage.ExtractingAudio)
                    return;
                Debug.Write(args.Precentage.ToString("A###") + " ");
                sb.Append(args.Precentage.ToString("A###") + " ");
                args.UIHandled = true;
            };
            yc.ProgresStateChanged += (sender, args) => {
                if (args.UIHandled || args.Stage != YoutubeStage.Downloading)
                    return;
                Debug.Write(args.Precentage.ToString("D###") + " ");
                sb.Append(args.Precentage.ToString("D###") + " ");
                args.UIHandled = true;
            };

            yc.ProgresStateChanged += (sender, args) => {
                if (args.UIHandled)
                    return;
                Debug.Write($"{{{args.Stage.ToString()}}}");
                sb.Append($"{{{args.Stage.ToString()}}}");
            };

            DownloadUrlResolver.FindHighestAudioQualityDownloadUrl(yc);

            try {
                ad.Execute();
                yc.WaitForThumbnail();
                Assert.IsTrue(File.Exists(yc.AudioPath?.FullName ?? "/"));
                Debug.WriteLine(yc.AudioPath?.FullName ?? "");
            } finally {
                if (yc.AudioPath != null && File.Exists(yc.AudioPath.FullName))
                    File.Delete(yc.AudioPath.FullName);
            }

            var events = Enum.GetValues(typeof(YoutubeStage)).Cast<YoutubeStage>()
                .Where(s =>
                    s != YoutubeStage.DecipheringUrls
                    && s != YoutubeStage.Downloading
                    && s != YoutubeStage.ExtractingAudio
                    && s != YoutubeStage.Undefined
                )
                .Select(ys => $"{{{ys}}}").ToArray();
            var c = sb.ToString();
            foreach (var @event in events)
                Assert.IsTrue(c.Contains(@event), $"c.Contains(YoutubeStage.{@event})");
        }
        public async Task ChooseBestVideo()
        {
            IEnumerable <VideoInfo> videoInfos = await DownloadUrlResolver.GetDownloadUrlsAsync("https://www.youtube.com/watch?v=vxMxYgkUcdU");

            var downloader = new AudioDownloader();

            Assert.IsNotNull(downloader.ChooseBest(videoInfos));
            Assert.IsTrue(downloader.ChooseBest(videoInfos).CanExtractAudio);
        }
Example #22
0
        public static async Task DownloadAudioAsync(VideoInfo videoInfo, string downloadPath, IObserver <double> progress)
        {
            string cleanedTitle = RemoveIllegalPathCharacters(videoInfo.Title);
            var    downloader   = new AudioDownloader(videoInfo, Path.Combine(downloadPath, cleanedTitle + videoInfo.AudioExtension));

            downloader.DownloadProgressChanged        += (sender, args) => progress.OnNext(args.ProgressPercentage * 0.95);
            downloader.AudioExtractionProgressChanged += (sender, args) => progress.OnNext(95 + args.ProgressPercentage * 0.05);

            await DownloadFromYoutube(downloader, new[] { typeof(IOException), typeof(WebException), typeof(AudioExtractionException) }, progress);
        }
        /// <summary>
        ///     Downloads context to audio, requires Url, Optional - VideoInfo (Default: Highest Quality), Optional - BaseDirectory
        /// </summary>
        public async static Task ToAudioAsync(this YoutubeContext context) {
            if (context==null)
                throw new ArgumentException(nameof(context));
            if (string.IsNullOrEmpty(context.Url))
                throw new ArgumentException(nameof(context.Url));
            
            if (context.VideoInfo == null)
                await context.FindHighestAudioQualityDownloadUrlAsync();

            var ad = new AudioDownloader(context);
            await ad.ExecuteAsync();
        }
Example #24
0
        async void Play()
        {
            if (_paused && _player != null)
            {
                _paused = false;
                //We are simply paused so just start again
                _player.Start();
                StartForeground();
                return;
            }

            if (_player == null)
            {
                IntializePlayer();
            }

            if (_player.IsPlaying)
            {
                return;
            }

            try
            {
                if (CurrentEpisode == null ||
                    Math.Abs(CurrentEpisode.Duration - CurrentEpisode.CurrentTime) < COMPARISON_EPSILON ||
                    !AudioDownloader.HasLocalFile(CurrentEpisode.RemoteUrl, CurrentEpisode.FileSize))
                {
                    return;
                }
                var file = new Java.IO.File(AudioDownloader.GetFilePath(CurrentEpisode.RemoteUrl));
                var fis  = new Java.IO.FileInputStream(file);

                // TODO reorganize it to play selected audio.
                // await player.SetDataSourceAsync(ApplicationContext, Net.Uri.Parse(Mp3
                await _player.SetDataSourceAsync(fis.FD);

                var focusResult = _audioManager.RequestAudioFocus(this, Stream.Music, AudioFocus.Gain);
                if (focusResult != AudioFocusRequest.Granted)
                {
                    Log.Debug(DEBUG_TAG, "Could not get audio focus");
                }

                _player.Prepare();
                CurrentPosition = (int)CurrentEpisode.CurrentTime;

                AquireWifiLock();
                StartForeground();
            }
            catch (Exception ex)
            {
                Log.Debug(DEBUG_TAG, "Unable to start playback: " + ex);
            }
        }
 /// <summary>
 ///     Downloads context to audio, requires Url, Optional - VideoInfo (Default: Highest Quality), Optional - BaseDirectory
 /// </summary>
 public static void ToAudio(this YoutubeContext context) {
     if (context==null)
         throw new ArgumentException(nameof(context));
     if (string.IsNullOrEmpty(context.Url))
         throw new ArgumentException(nameof(context.Url));
     
     if (context.VideoInfo == null)
         context.FindHighestAudioQualityDownloadUrl();
     
     var ad = new AudioDownloader(context);
     ad.Execute();
 }
Example #26
0
        public void DownloadAudio(string link)
        {
            // Our test youtube link
            //string link = "insert youtube link";

            /*
             * Get the available video formats.
             * We'll work with them in the video and audio download examples.
             */
            IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link);

            /*
             * We want the first extractable video with the highest audio quality.
             */
            VideoInfo video = videoInfos
                              .Where(info => info.CanExtractAudio)
                              .OrderByDescending(info => info.AudioBitrate)
                              .First();

            /*
             * If the video has a decrypted signature, decipher it
             */
            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }

            /*
             * Create the audio downloader.
             * The first argument is the video where the audio should be extracted from.
             * The second argument is the path to save the audio file.
             */
            string fileName = video.Title;

            fileName = Regex.Replace(fileName, @"[^\w\.@-]", "", RegexOptions.None, TimeSpan.FromSeconds(1.5));
            var audioDownloader = new AudioDownloader(video, Path.Combine(downloadLocation, fileName + video.AudioExtension));


            // Register the progress events. We treat the download progress as 85% of the progress and the extraction progress only as 15% of the progress,
            // because the download will take much longer than the audio extraction.
            audioDownloader.DownloadProgressChanged        += (sender, args) => Console.WriteLine(args.ProgressPercentage * 0.85);
            audioDownloader.AudioExtractionProgressChanged += (sender, args) => Console.WriteLine(85 + args.ProgressPercentage * 0.15);

            if (!File.Exists(Path.Combine(downloadLocation, fileName + video.AudioExtension)))
            {
                /*
                 * Execute the audio downloader.
                 * For GUI applications note, that this method runs synchronously.
                 */
                audioDownloader.Execute();
            }
        }
Example #27
0
        static void Main(string[] args)
        {
            var mp3OutputFolder = "c:/@mp3/";

            var downloader = new AudioDownloader("http://soundcloud.com/skunkfunk/grappig", Guid.NewGuid().ToString(), mp3OutputFolder, false);

            downloader.ProgressDownload += downloader_ProgressDownload;
            downloader.FinishedDownload += downloader_FinishedDownload;
            downloader.Download();


            Console.ReadLine();
        }
Example #28
0
        /// <summary>
        /// The thread's method which in place executes the audiodownloader
        /// </summary>
        private void DownloadThreadMethod()
        {
            AudioDownloader audioDownloader = new AudioDownloader(this.VideoInfo, Application.StartupPath + "/_SESSIONS/" + this.SessionID + "/" + VideoInfo.Title + VideoInfo.AudioExtension, this.Url);

            audioDownloader.DownloadProgressChanged        += new EventHandler <ProgressEventArgs>(audioDownloader_DownloadProgressChanged);
            audioDownloader.AudioExtractionProgressChanged += new EventHandler <ProgressEventArgs>(audioDownloader_AudioExtractionProgressChanged);
            audioDownloader.Execute();

            while (!this.IsComplete)
            {
                ///
            }
        }
Example #29
0
        private void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            AudioDownloader downloader = new AudioDownloader(txturlBox.Text, filename, folder);

            Invoke(new MethodInvoker(delegate
            {
                txtfilenameBox.Text = downloader.OutputName;
            }
                                     ));
            downloader.ProgressDownload += Downloader_ProgressDownload;
            downloader.FinishedDownload += Downloader_FinishedDownload;
            downloader.ErrorDownload    += Downloader_ErrorDownload;
            downloader.Download();
        }
Example #30
0
 public UrlProcessService(
     IEntryRepository repository, IUnitOfWork unitOfWork,
     AudioDownloader downloader,
     IPageParser parser,
     IYouTubeParser youTubeParser,
     ILogger <UrlProcessService> logger, IRealTimeUpdater realtimeUpdater,
     IMapper mapper) : base(logger, realtimeUpdater, mapper)
 {
     _repository    = repository;
     _unitOfWork    = unitOfWork;
     _downloader    = downloader;
     _parser        = parser;
     _youTubeParser = youTubeParser;
 }
Example #31
0
        static void Main(string[] args)
        {
            var mp3OutputFolder = "c:/@mp3/";

            var downloader = new AudioDownloader("https://www.youtube.com/watch?v=clhvCRwUjD4", Guid.NewGuid().ToString(), mp3OutputFolder);

            downloader.ProcessObject     = new song();
            downloader.ProgressDownload += downloader_ProgressDownload;
            downloader.FinishedDownload += downloader_FinishedDownload;
            downloader.Download();


            Console.ReadLine();
        }
Example #32
0
        static void Main(string[] args)
        {
            var mp3OutputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Audio");

            var downloader = new AudioDownloader(Path.Combine(Directory.GetCurrentDirectory(), "Binaries"), "https://www.youtube.com/watch?v=enBllfqkMEw", Guid.NewGuid().ToString(), mp3OutputFolder);

            downloader.ProcessObject     = new song();
            downloader.ProgressDownload += downloader_ProgressDownload;
            downloader.FinishedDownload += downloader_FinishedDownload;
            downloader.Download();


            Console.ReadLine();
        }
Example #33
0
        void DownloadAudioFrom(Downloadable InVideo, int count)
        {
            InVideo.Preparing = true;
            ListDelegate ld = new ListDelegate(Program.frm.UpdateList);

            Program.frm.Invoke(ld);

            string link        = InVideo.Url;
            string countPrefix = count.ToString();

            countPrefix = countPrefix.PadLeft(padLeft, '0');

            VideoInfo video = DownloadUrlResolver.GetDownloadUrls(link);

            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }

            char[] legalTitleArray = video.Title.ToCharArray();
            string legalTitle      = "";

            foreach (char c in legalTitleArray)
            {
                if (!(c == '/' || c == '\\' || c == ':' || c == '*' || c == '?' || c == '"' || c == '<' || c == '>' || c == '|'))
                {
                    legalTitle += c;
                }
            }

            if (incremental)
            {
                var audioDownloader = new AudioDownloader(video, savePath + @"\" + countPrefix + " " + legalTitle + video.AudioExtension);
                audioDownloader.DownloadProgressChanged        += (sender, _args) => DownloadProgress(_args.ProgressPercentage, InVideo);
                audioDownloader.AudioExtractionProgressChanged += (sender, _args) => ExtractionProgress(_args.ProgressPercentage, InVideo);
                audioDownloader.Execute();
            }
            else
            {
                var audioDownloader = new AudioDownloader(video, savePath + @"\" + legalTitle + video.AudioExtension);
                audioDownloader.DownloadProgressChanged        += (sender, _args) => DownloadProgress(_args.ProgressPercentage, InVideo);
                audioDownloader.AudioExtractionProgressChanged += (sender, _args) => ExtractionProgress(_args.ProgressPercentage, InVideo);
                audioDownloader.Execute();
            }

            lock (threadLocker)
            {
                Program.frm.remaining--;
            }
        }
        public void UrlDownloadingFileAlreadyExistsTest()
        {
            var yc = new YoutubeContext(Url) {BaseDirectory = new DirectoryInfo(Path.GetTempPath())};
            var yc2 = new YoutubeContext(Url) {BaseDirectory = new DirectoryInfo(Path.GetTempPath())};
            DownloadUrlResolver.FindHighestAudioQualityDownloadUrlAsync(yc).Wait();
            DownloadUrlResolver.FindHighestAudioQualityDownloadUrlAsync(yc2).Wait();

            if (yc.VideoInfo.RequiresDecryption)
                DownloadUrlResolver.DecryptDownloadUrl(yc.VideoInfo);
            var tf = Path.GetTempPath();
            var ad = new AudioDownloader(yc);
            var ad2 = new AudioDownloader(yc2);
            try {
                ad.Execute();
                ad2.Execute();
                Debug.WriteLine(yc.AudioPath.FullName);
                Debug.WriteLine(yc2.AudioPath.FullName);
                Assert.IsTrue(File.Exists(yc.AudioPath.FullName));
                Assert.IsTrue(File.Exists(yc2.AudioPath.FullName));
                Assert.IsTrue(yc.AudioPath.FullName != yc2.AudioPath.FullName);
            } finally {
                if (ad != null && File.Exists(yc.AudioPath.FullName))
                    File.Delete(yc.AudioPath.FullName);
                if (ad2 != null && File.Exists(yc2.AudioPath.FullName))
                    File.Delete(yc2.AudioPath.FullName);
            }
        }
        public void UrlDownloadingTest()
        {
            var yc = new YoutubeContext(Url) {BaseDirectory = new DirectoryInfo(Path.GetTempPath())};
            DownloadUrlResolver.FindHighestAudioQualityDownloadUrl(yc);

            var ad = new AudioDownloader(yc);
            try {
                ad.Execute();
                Assert.IsTrue(File.Exists(yc.AudioPath.FullName));
                Debug.WriteLine(yc.AudioPath.FullName);
            } finally {
                if (yc != null && File.Exists(yc.AudioPath.FullName))
                    File.Delete(yc.AudioPath.FullName);
            }
        }