static async Task Main(string username   = "",
                               string channelId  = "",
                               string playlistId = "",
                               string directory  = "", string ffmpegPath = "", bool audio = false, bool youtubeMusic = false, bool captions = false, int maxPage = 0)
        {
            if (string.IsNullOrEmpty(ffmpegPath))
            {
                Converter = new YoutubeConverter(Client);
            }
            else
            {
                Converter = new YoutubeConverter(Client, ffmpegPath);
            }

            ProgressBar.ProgressChanged += ProgressBar_ProgressChanged;


            if (captions)
            {
                await GetCaptionsAsync(directory, maxPage, username, channelId, playlistId);
            }
            else if (!string.IsNullOrEmpty(playlistId))
            {
                await GetPlaylistAsync(directory, maxPage, playlistId, audio, youtubeMusic);
            }
            else
            {
                await GetChannelAsync(directory, maxPage, username, channelId, audio, youtubeMusic);
            }
        }
Exemple #2
0
        public async Task <string> DownloadVideoTask(string url)
        {
            try
            {
                var client = new YoutubeClient();
                var id     = YoutubeClient.ParseVideoId(url);
                var video  = await client.GetVideoAsync(id);

                var title    = video.Title;
                var author   = video.Author;
                var duration = video.Duration;
                var fileName = DateTime.Now.ToString("MM_dd_yyyy_HH_mm_ss");

                var converter = new YoutubeConverter(client, "C:\\ffmpeg-4.2.2\\bin\\ffmpeg.exe");

                await converter.DownloadVideoAsync(id, $"C:\\Temp\\{fileName}.wav");

                var path = $"C:\\Temp\\{fileName}.wav";

                Console.WriteLine("[DownloadVideoTask] - Done Download Video");

                return(path);
            }
            catch (Exception e)
            {
                Console.WriteLine($"[DownloadVideoTask] - Error {e}");

                return(null);
            }
        }
Exemple #3
0
        public async Task <RuntimeResult> MusicAsync([Remainder] string search)
        {
            var channel = (Context.User as IGuildUser)?.VoiceChannel;

            if (Context.Guild.CurrentUser.VoiceChannel != null)
            {
                return(Result.FromError("I'm already in a voice channel!"));
            }
            if (channel == null)
            {
                return(Result.FromError("You need to be in a voice channel to do that."));
            }

            var message = await ReplyAsync($"searching for `{search}` on YouTube...");

            var client    = new YoutubeClient();
            var vidSearch = await client.SearchVideosAsync(search, 1) as List <YoutubeExplode.Models.Video>;

            var searchArray = vidSearch.ToArray();

            if (searchArray.Length <= 0)
            {
                return(Result.FromError($"No videos could be found for the query `{search}`"));
            }
            if (searchArray[0].Duration > TimeSpan.FromHours(1))
            {
                return(Result.FromError("Videos must be no longer than one hour be played."));
            }

            await message.ModifyAsync(msg => msg.Content = $"Found video! (`{searchArray[0].Title}` uploaded by `{searchArray[0].Author}`)\nPreparing audio...");

            var info = await client.GetVideoMediaStreamInfosAsync(searchArray[0].Id);

            var converter = new YoutubeConverter(client);
            await converter.DownloadVideoAsync(info, $"song_{Context.Guild.Id}.opus", "opus");

            await message.ModifyAsync(msg => msg.Content = $"Joining channel and playing `{searchArray[0].Title}`");

            var aClient = await channel.ConnectAsync();

            using (var ffmpeg = CreateStream($"song_{Context.Guild.Id}.opus"))
                using (var output = ffmpeg.StandardOutput.BaseStream)
                    using (var discord = aClient.CreatePCMStream(AudioApplication.Mixed))
                    {
                        try
                        {
                            aStreams.Add(Context.Guild.Id, discord);
                            pauseCancelTokens.Add(Context.Guild.Id, new CancellationTokenSource());
                            pauseBools.Add(Context.Guild.Id, false);
                            await PausableCopyToAsync(output, discord, Context.Guild.Id, 4096);
                        }

                        finally { await discord.FlushAsync(); }
                    }

            await Context.Guild.CurrentUser.VoiceChannel.DisconnectAsync();

            return(Result.FromSuccess());
        }
Exemple #4
0
        public async Task Download <T> (string url, T media) where T : IMedia
        {
            var converter = new YoutubeConverter();
            var videoId   = url;

            if (url.Contains("youtu"))
            {
                videoId = YoutubeClient.ParseVideoId(url);
            }
            await converter.DownloadVideoAsync($"{videoId}", Path.Combine(media.FileDirectory, $"{media.FileName}.mp4"));
        }
Exemple #5
0
        public async Task YoutubeConverter_DownloadVideoAsync_Test(
            [ValueSource(typeof(TestData), nameof(TestData.VideoIds))] string videoId,
            [ValueSource(typeof(TestData), nameof(TestData.OutputFormats))] string format)
        {
            var converter = new YoutubeConverter();

            Directory.CreateDirectory(TempDirPath);
            var outputFilePath = Path.Combine(TempDirPath, $"{Guid.NewGuid()}");

            await converter.DownloadVideoAsync(videoId, outputFilePath, format);

            var fileInfo = new FileInfo(outputFilePath);

            Assert.That(fileInfo.Exists, Is.True);
            Assert.That(fileInfo.Length, Is.GreaterThan(0));
        }
Exemple #6
0
        public async void Run(SdjMainViewModel sdjMainViewModel, List <string> parameters)
        {
            var dj = JsonConvert.DeserializeObject <Dj>(parameters[0]);

            Console.WriteLine(FilesPath.Instance.MusicFolder);
            var converter = new YoutubeConverter();

            foreach (var track in dj.Track)
            {
                if (File.Exists($@"{FilesPath.Instance.MusicFolder}{track.Id}.mp4"))
                {
                    continue;
                }
                await converter.DownloadVideoAsync(track.Id, $@"{FilesPath.Instance.MusicFolder}{track.Id}.mp4");
            }
        }
Exemple #7
0
        public async Task <IActionResult> Download(string id)
        {
            var client         = new YoutubeClient();
            var converter      = new YoutubeConverter(client);
            var streamManifest = await client.Videos.Streams.GetManifestAsync(id);

            var    title            = client.Videos.GetAsync(id).Result.Title;
            string path             = $"{id}.mp3";
            var    streamInfo       = streamManifest.GetAudioOnly().WithHighestBitrate();
            var    mediaStreamInfos = new IStreamInfo[] { streamInfo };
            await converter.DownloadAndProcessMediaStreamsAsync(mediaStreamInfos, path, "mp3");

            byte[] buff = System.IO.File.ReadAllBytes(path);
            System.IO.File.Delete(path);
            return(File(buff, "application/force-download", $"{title}.mp3"));
        }
Exemple #8
0
        private static void DownloadVideo(IYoutubeClient client, Video video, string downloadFolder, string videoFileNameBase, IProgress <double> progress)
        {
            var converter = new YoutubeConverter(client, Ffmpeg.DefaultFilePath);

            var mediaStreamInfoSet = client.GetVideoMediaStreamInfosAsync(video.Id).Result;
            var videoStreamInfo    = mediaStreamInfoSet.Video.OrderByDescending(info => info.VideoQuality).ThenByDescending(info => info.Framerate).First();
            var audioStreamInfo    = mediaStreamInfoSet.Audio.OrderByDescending(info => info.Bitrate).First();

            var extension = videoStreamInfo.Container.GetFileExtension();

            converter.DownloadAndProcessMediaStreamsAsync(
                new MediaStreamInfo[] { videoStreamInfo, audioStreamInfo },
                Path.Combine(downloadFolder, videoFileNameBase + $".{extension}"),
                extension,
                progress)
            .Wait();
        }
Exemple #9
0
        public async Task <string> DownloadVideoOptionsTask(string url)
        {
            //try
            //{
            var client = new YoutubeClient();

            var id = YoutubeClient.ParseVideoId(url);

            var video = await client.GetVideoAsync(id);

            var author = video.Author;

            var converter = new YoutubeConverter(client, "C:\\ffmpeg-4.2.2\\bin\\ffmpeg.exe");

            var mediaStreamInfoSet = await client.GetVideoMediaStreamInfosAsync(id);

            // Select video stream
            var videoStreamInfo = mediaStreamInfoSet.Video.FirstOrDefault(s => s.VideoQualityLabel == "240p");

            // Select audio stream
            var audioStreamInfo = mediaStreamInfoSet.Audio.First(s => s.Bitrate == 128);

            // Combine them into a collection
            var mediaStreamInfos = new MediaStreamInfo[] { audioStreamInfo, videoStreamInfo };

            // Download and process them into one file
            await converter.DownloadAndProcessMediaStreamsAsync(mediaStreamInfos, $"C:\\Temp\\{author}.wav", "wav");

            var path = $"C:\\Temp\\{author}.wav";

            Console.WriteLine("[DownloadVideoTask] - Done Download Video");

            return(path);
            //}
            //catch (Exception e)
            //{
            //    Console.WriteLine($"[DownloadVideoTask] - Error {e}");

            //    return null;
            //}
        }
Exemple #10
0
        /// <summary>
        /// Download the video in .mp4 or audio in .mp3 locally if it is valid.
        /// </summary>
        /// <param name="videoToDownload">The URL of the video.</param>
        /// <param name="audioOnly">If only the audio in .mp3 is required.</param>
        /// <param name="outputDirectory">The default directory is the desktop, but can be specified.</param>
        /// <param name="progress">The IProgress to monitor the download status.</param>
        /// <returns></returns>
        public async Task DownloadFileAsync(VideoInfo videoToDownload, bool audioOnly = false, Uri outputDirectory = null, IProgress <double> progress = null)
        {
            if (outputDirectory == null)
            {
                outputDirectory = new Uri(Environment.GetFolderPath(Environment.SpecialFolder.Desktop));
            }

            var    client    = new YoutubeClient();
            var    converter = new YoutubeConverter(client, ffmpegPath);
            string ext;

            if (audioOnly)
            {
                ext = ".mp3";
            }
            else
            {
                ext = ".mp4";
            }
            await converter.DownloadVideoAsync(videoToDownload.VideoMetadata.Id, Path.Combine(outputDirectory.LocalPath, SanitizeFilename(videoToDownload.VideoMetadata.Title) + ext), ext.Substring(1), progress);
        }
Exemple #11
0
        public async Task YoutubeConverter_DownloadVideoAsync_Test(
            [ValueSource(typeof(TestData), nameof(TestData.VideoIds))] string videoId,
            [ValueSource(typeof(TestData), nameof(TestData.OutputFormats))] string format)
        {
            // Arrange
            Directory.CreateDirectory(TempDirPath);
            var outputFilePath = Path.Combine(TempDirPath, Guid.NewGuid().ToString());
            var converter      = new YoutubeConverter();

            // Act
            await converter.DownloadVideoAsync(videoId, outputFilePath, format);

            var fileInfo = new FileInfo(outputFilePath);

            // Assert
            Assert.Multiple(() =>
            {
                Assert.That(fileInfo.Exists, Is.True, "File exists");
                Assert.That(fileInfo.Length, Is.GreaterThan(0), "File size");
            });
        }
Exemple #12
0
        static async Task Main(string[] args)
        {
            var client    = new YoutubeClient();
            var converter = new YoutubeConverter(client); // re-using the same client instance for efficiency, not required

            // Get media stream info set
            var mediaStreamInfoSet = await client.GetVideoMediaStreamInfosAsync("NIJHqNWMtAw");

            // Select audio stream
            var audioStreamInfo = mediaStreamInfoSet.Audio.WithHighestBitrate();

            // Select video stream
            var videoStreamInfo = mediaStreamInfoSet.Video.FirstOrDefault(s => s.VideoQualityLabel.Contains("360"));

            // Combine them into a collection
            var mediaStreamInfos = new MediaStreamInfo[] { audioStreamInfo, videoStreamInfo };

            // Download and process them into one file
            await converter.DownloadAndProcessMediaStreamsAsync(mediaStreamInfos, @"video.mp4", "mp4", new MyProgress());

            Console.WriteLine("Done");
        }
        private async Task GetVideo(string url)
        {
            txtStatus.Text += $"Fetching\n{url}\n";
            var converter = new YoutubeConverter();
            var id        = YoutubeClient.ParseVideoId(url);
            var client    = new YoutubeClient();

            var video = await client.GetVideoAsync(id);

            string path = @"/mnt/sdcard/Downloads/YoutubeToMp3/";

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

            txtStatus.Text += $"Get Stream Info Set...\n";
            var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(id);

            if (option == "MP3")
            {
                txtStatus.Text += $"Geting Audio...\n";
                var streamInfo = streamInfoSet.Audio.WithHighestBitrate();


                var ext = streamInfo.Container.GetFileExtension();

                txtStatus.Text += $"Saving to file...\n";
                // Download stream to file
                try
                {
                    string audioPath = $@"{path}{video.Title.Replace('/', ' ')}.";
                    await client.DownloadMediaStreamAsync(streamInfo, $@"{audioPath}.{ext}");


                    //var mediaStreamInfos = new MediaStreamInfo[] { streamInfo };
                    //await converter.DownloadAndProcessMediaStreamsAsync(mediaStreamInfos, $@"{audioPath}.mp3", "mp3");
                }
                catch (Exception e)
                {
                    txtStatus.Text += $"\n=======================\nReport this error to me\n{e.Message}\n=======================\n\n";
                }
            }
            else
            {
                txtStatus.Text += $"Geting Video...\n";
                var streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality();

                var ext = streamInfo.Container.GetFileExtension();

                txtStatus.Text += $"Saving to file...\n";
                // Download stream to file
                try
                {
                    await client.DownloadMediaStreamAsync(streamInfo, $@"{path}{video.Title.Replace('/', ' ')}.{ext}");
                }
                catch (Exception e)
                {
                    txtStatus.Text += $"\n=======================\nReport this error to me\n{e.Message}\n=======================\n\n";
                }
            }

            txtStatus.Text += $"{CurrentCount + 1}/{totalCount} completed\n";
            CurrentCount++;

            if (totalCount == CurrentCount)
            {
                txtStatus.Text       += "\nTask Completed Successfully!\nIf you found bugs and errors please contact me.\n\nFB: Jamuel Galicia\n";
                btnDownload.IsEnabled = true;
                GC.Collect();
            }
        }