コード例 #1
0
        private static async Task DownloadAndConvertVideoAsync(string id)
        {
            Console.WriteLine($"Working on video [{id}]...");

            // Get video info
            var video = await YoutubeClient.GetVideoAsync(id);

            var cleanTitle = video.Title.Replace(Path.GetInvalidFileNameChars(), '_');

            Console.WriteLine($"{video.Title}");

            // Download video as mp3
            Console.WriteLine("Downloading...");
            Directory.CreateDirectory(OutputDirectoryPath);
            var outputFilePath = Path.Combine(OutputDirectoryPath, $"{cleanTitle}.mp3");
            await YoutubeConverter.DownloadVideoAsync(id, outputFilePath);

            // Edit mp3 metadata
            Console.WriteLine("Writing metadata...");
            var idMatch = Regex.Match(video.Title, @"^(?<artist>.*?)-(?<title>.*?)$");
            var artist  = idMatch.Groups["artist"].Value.Trim();
            var title   = idMatch.Groups["title"].Value.Trim();

            using (var meta = TagLib.File.Create(outputFilePath))
            {
                meta.Tag.Performers = new[] { artist };
                meta.Tag.Title      = title;
                meta.Save();
            }

            Console.WriteLine($"Downloaded and converted video [{id}] to [{outputFilePath}]");
        }
コード例 #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);
            }
        }
コード例 #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());
        }
コード例 #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"));
        }
コード例 #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));
        }
コード例 #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");
            }
        }
コード例 #7
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);
        }
コード例 #8
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");
            });
        }