Exemplo n.º 1
0
        public async Task SendYTAudio(IGuild guild, IMessageChannel channel, string url)
        {
            var client = new YoutubeClient();

            string id = NormalizeId(url);

            var videoInfo = await client.GetVideoInfoAsync(id);

            var    streamInfo = videoInfo.AudioStreams.OrderBy(s => s.Bitrate).Last();
            string path       = "C:\\Users\\Yeo\\documents\\visual studio 2017\\Projects\\Shucks\\Shucks\\Audio\\" + $"{videoInfo.Title}.{streamInfo.Container.GetFileExtension()}";

            try
            {
                using (var input = await client.GetMediaStreamAsync(streamInfo))
                    using (var file = File.Create(path))
                    {
                        await input.CopyToAsync(file);
                    }
                await SendAudioAsync(guild, channel, path);
            }
            finally
            {
                File.Delete(path);
            }
        }
Exemplo n.º 2
0
        public async Task YoutubeClient_GetVideoInfoAsync_Paid_Test()
        {
            string id = (string)TestContext.DataRow["Id"];

            var client = new YoutubeClient();
            await Assert.ThrowsExceptionAsync <VideoRequiresPurchaseException>(() => client.GetVideoInfoAsync(id));
        }
Exemplo n.º 3
0
        public static async Task <string> GetMusicVideo(string videoId, ChromiumWebBrowser youtubePlayer)
        {
            //use video id to get the song
            VideoId = videoId;

#if OFFLINE_IMPLEMENTED
            if (!FilePaths.InCache())
            {
                Console.WriteLine("Video not in cache; video is downloading now");
                return(await GetMusic.DownloadVideo(youtubePlayer));
            }
            // Client
            var client    = new YoutubeClient();
            var videoInfo = await client.GetVideoInfoAsync(VideoId);

            // Print metadata
            // Console.WriteLine($"Id: {videoInfo.Id} | Title: {videoInfo.Title} | Author: {videoInfo.Author.Title}");
            var fullName = videoInfo.Title;
            //code for the video library api
            var saveName = FilePaths.RemoveIllegalPathCharacters(fullName.Replace("- YouTube", ""));
            saveName = saveName.Replace("_", "");
            string savePath = Path.Combine(FilePaths.SaveLocation(),
                                           (saveName));

            return(savePath);
#endif
            return(await DownloadVideo(youtubePlayer));
        }
Exemplo n.º 4
0
        public async Task YoutubeClient_GetVideoInfoAsync_NonExisting_Test()
        {
            string id = (string)TestContext.DataRow["Id"];

            var client = new YoutubeClient();
            await Assert.ThrowsExceptionAsync <VideoNotAvailableException>(() => client.GetVideoInfoAsync(id));
        }
Exemplo n.º 5
0
        private async void GetVideoInfoAsync()
        {
            // Check params
            if (VideoId.IsBlank())
            {
                return;
            }

            IsBusy = true;
            IsProgressIndeterminate = true;

            // Reset data
            VideoInfo = null;

            // Parse URL if necessary
            string id;

            if (!YoutubeClient.TryParseVideoId(VideoId, out id))
            {
                id = VideoId;
            }

            // Perform the request
            VideoInfo = await _client.GetVideoInfoAsync(id);

            IsProgressIndeterminate = false;
            IsBusy = false;
        }
Exemplo n.º 6
0
        public static async Task <VideoInfo> GetVideoInfo(string link)
        {
            var name      = link.Split('=')[1];
            var client    = new YoutubeClient();
            var videoInfo = await client.GetVideoInfoAsync(name);

            return(videoInfo);
        }
Exemplo n.º 7
0
        static async Task Run(string api, string temp, string target, string quality)
        {
            api    = api ?? throw new ArgumentNullException(nameof(api));
            temp   = temp ?? throw new ArgumentNullException(nameof(temp));
            target = target ?? throw new ArgumentNullException(nameof(target));

            var songNames = ExtractSongNamesFromSite();

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

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

            foreach (var item in songNames)
            {
                var id = GetYoutubeVideoID(item, api);

                var client = new YoutubeClient();
                var video  = await client.GetVideoInfoAsync(id);

                var streaminfo = video.AudioStreams.OrderBy(x => x.Bitrate).Last();

                string filename = Path.Combine(temp, $"{video.Title}.{streaminfo.Container.GetFileExtension()}");
                string fname    = Path.Combine(target, $"{video.Title}.mp3");

                Console.WriteLine($"Rozpoczęto pobieranie: {item}");
                await client.DownloadMediaStreamAsync(streaminfo, filename);

                Console.WriteLine($"Zakończono pobieranie: {item}");

                Console.WriteLine($"Rozpoczynanie konwersji audio dla: {item}");

                ProcessStartInfo info = new ProcessStartInfo("ffmpeg.exe");
                info.CreateNoWindow         = false;
                info.RedirectStandardOutput = true;
                info.UseShellExecute        = false;
                info.WindowStyle            = ProcessWindowStyle.Hidden;
                info.Arguments = $"-i \"{filename}\" -vn -ab {quality}k -ar 44100 -y \"{fname}\"";
                var proc = Process.Start(info);

                //while (!proc.StandardOutput.EndOfStream)
                //{
                //    Console.WriteLine(proc.StandardOutput.ReadLine());
                //}

                proc.WaitForExit();

                Console.WriteLine($"Zakończono konwersję audio dla: {item}");
            }

            Console.WriteLine("Zakończono pobieranie i konwertowanie");
            _isFinished = true;
        }
Exemplo n.º 8
0
        public async Task YoutubeClient_GetVideoInfoAsync_Test()
        {
            string id = (string)TestContext.DataRow["Id"];

            var client    = new YoutubeClient();
            var videoInfo = await client.GetVideoInfoAsync(id);

            Assert.That.IsSet(videoInfo);
            Assert.AreEqual(id, videoInfo.Id);
        }
Exemplo n.º 9
0
        public async Task YoutubeClient_GetVideoInfoAsync_Signed_Test()
        {
            // Video that uses signature cipher

            var client    = new YoutubeClient();
            var videoInfo = await client.GetVideoInfoAsync("9bZkp7q19f0");

            Assert.That.IsSet(videoInfo);
            Assert.AreEqual("9bZkp7q19f0", videoInfo.Id);
        }
Exemplo n.º 10
0
        public async Task YoutubeClient_GetVideoInfoAsync_SignedRestricted_Test()
        {
            // Video that uses signature cipher and is also age-restricted

            var client    = new YoutubeClient();
            var videoInfo = await client.GetVideoInfoAsync("SkRSXFQerZs");

            Assert.That.IsSet(videoInfo);
            Assert.AreEqual("SkRSXFQerZs", videoInfo.Id);
        }
Exemplo n.º 11
0
        public async Task YoutubeClient_GetClosedCaptionTrackAsync_Normal_Test()
        {
            var client    = new YoutubeClient();
            var videoInfo = await client.GetVideoInfoAsync("_QdPW8JrYzQ");

            var trackInfo = videoInfo.ClosedCaptionTracks.First();
            var track     = await client.GetClosedCaptionTrackAsync(trackInfo);

            Assert.That.IsSet(track);
        }
Exemplo n.º 12
0
        public async Task YoutubeClient_GetVideoInfoAsync_CannotEmbed_Test()
        {
            // Video that cannot be embedded outside of Youtube

            var client    = new YoutubeClient();
            var videoInfo = await client.GetVideoInfoAsync("_kmeFXjjGfk");

            Assert.That.IsSet(videoInfo);
            Assert.AreEqual("_kmeFXjjGfk", videoInfo.Id);
        }
Exemplo n.º 13
0
        public async Task YoutubeClient_GetVideoInfoAsync_Normal_Test()
        {
            // Most common video type

            var client    = new YoutubeClient();
            var videoInfo = await client.GetVideoInfoAsync("_QdPW8JrYzQ");

            Assert.That.IsSet(videoInfo);
            Assert.AreEqual("_QdPW8JrYzQ", videoInfo.Id);
        }
Exemplo n.º 14
0
        private async void btnPlaylist_Click(object sender, EventArgs e)
        {
            YoutubeClient youtubeClient = new YoutubeClient();

            if (YoutubeClient.TryParsePlaylistId(tbPlaylistUrl.Text, out string playlistId))
            {
                var playlistInfos = await youtubeClient.GetPlaylistInfoAsync(playlistId);

                var firstVideo = await youtubeClient.GetVideoInfoAsync(playlistInfos.Videos[0].Id);
            }
        }
Exemplo n.º 15
0
        public async Task YoutubeClient_GetClosedCaptionTrackAsync_Test()
        {
            string id = (string)TestContext.DataRow["Id"];

            var client    = new YoutubeClient();
            var videoInfo = await client.GetVideoInfoAsync(id);

            var trackInfo = videoInfo.ClosedCaptionTracks.First();
            var track     = await client.GetClosedCaptionTrackAsync(trackInfo);

            Assert.That.IsSet(track);
        }
        public async Task GetVideoInfoAsync_UnsignedUnrestrictedNonAdaptive_Test()
        {
            var videoInfo = await _client.GetVideoInfoAsync("LsNPjFXIPT8", false, false);

            Assert.IsNotNull(videoInfo);
            Assert.AreEqual("LsNPjFXIPT8", videoInfo.Id);
            Assert.AreEqual("kyoumei no true force iyasine", videoInfo.Title);
            Assert.AreEqual("Tyrrrz", videoInfo.Author);
            Assert.IsTrue(103 <= videoInfo.Length.TotalSeconds);
            Assert.IsTrue(0 <= videoInfo.AverageRating);
            Assert.IsTrue(1 <= videoInfo.ViewCount);
            Assert.IsNotNull(videoInfo.Keywords);
            Assert.AreEqual(0, videoInfo.Keywords.Length);
            Assert.IsTrue(videoInfo.Keywords.All(k => !string.IsNullOrWhiteSpace(k)));
            Assert.IsNotNull(videoInfo.Watermarks);
            Assert.AreEqual(2, videoInfo.Watermarks.Length);

            Assert.IsFalse(videoInfo.HasClosedCaptions);
            Assert.IsTrue(videoInfo.IsEmbeddingAllowed);
            Assert.IsTrue(videoInfo.IsListed);
            Assert.IsTrue(videoInfo.IsRatingAllowed);
            Assert.IsFalse(videoInfo.IsMuted);

            Assert.IsNotNull(videoInfo.Streams);
            Assert.IsTrue(0 < videoInfo.Streams.Length);
            //Assert.AreEqual(9, videoInfo.Streams.Length);
            foreach (var streamInfo in videoInfo.Streams)
            {
                Assert.IsNotNull(streamInfo.Url);
                Assert.IsNotNull(streamInfo.FileExtension);
            }
        }
        public async Task GetVideoInfoAsync_UnsignedUnrestricted_Test()
        {
            _client.ShouldGetVideoFileSizes = false;
            var videoInfo = await _client.GetVideoInfoAsync("LsNPjFXIPT8");

            Assert.IsNotNull(videoInfo);

            // Basic meta data
            Assert.AreEqual("LsNPjFXIPT8", videoInfo.Id);
            Assert.AreEqual("kyoumei no true force iyasine", videoInfo.Title);
            Assert.AreEqual("Tyrrrz", videoInfo.Author);
            Assert.IsTrue(103 <= videoInfo.Length.TotalSeconds);
            Assert.IsTrue(1 <= videoInfo.ViewCount);
            Assert.IsTrue(0 <= videoInfo.AverageRating);

            // Keywords
            Assert.IsNotNull(videoInfo.Keywords);
            Assert.AreEqual(0, videoInfo.Keywords.Length);

            // Watermarks
            Assert.IsNotNull(videoInfo.Watermarks);
            Assert.AreEqual(2, videoInfo.Watermarks.Length);

            // Flags
            Assert.IsFalse(videoInfo.HasClosedCaptions);
            Assert.IsTrue(videoInfo.IsEmbeddingAllowed);
            Assert.IsTrue(videoInfo.IsListed);
            Assert.IsTrue(videoInfo.IsRatingAllowed);
            Assert.IsFalse(videoInfo.IsMuted);

            // Streams
            Assert.IsNotNull(videoInfo.Streams);
            Assert.IsTrue(9 <= videoInfo.Streams.Length);
            foreach (var streamInfo in videoInfo.Streams)
            {
                Assert.IsNotNull(streamInfo.Url);
            }

            // Captions
            Assert.IsNotNull(videoInfo.CaptionTracks);
            Assert.AreEqual(0, videoInfo.CaptionTracks.Length);
        }
Exemplo n.º 18
0
        private static async void download(string link)
        {
            try
            {
                link = NormalizeId(link);

                // Get the video info
                Console.WriteLine("Loading...");
                // Client
                var client = new YoutubeClient();

                var videoInfo = await client.GetVideoInfoAsync(link);

                Console.WriteLine('-');

                // Print metadata
                Console.WriteLine($"Id: {videoInfo.Id} | Title: {videoInfo.Title} | Author: {videoInfo.Author.Title}");

                // Get the most preferable stream
                Console.WriteLine("Looking for the best mixed stream...");
                var streamInfo = videoInfo.AudioStreams
                                 .OrderBy(s => s.Bitrate)
                                 .Last();
                string normalizedFileSize = NormalizeFileSize(streamInfo.ContentLength);
                Console.WriteLine($"Quality: {streamInfo.Bitrate} | Container: {streamInfo.Container} | Size: {normalizedFileSize}");

                // Compose file name, based on metadata
                string fileExtension  = streamInfo.Container.GetFileExtension();
                string downloadFolder = @"C:\temp\";
                string fileName       = $"{downloadFolder}{videoInfo.Title}.{fileExtension}";

                // Remove illegal characters from file name

                // Download video
                Console.WriteLine($"Downloading to [{fileName}]...");

                var progress = new Progress <double>(p => Console.Title = $"YoutubeExplode Demo [{p:P0}]");
                await client.DownloadMediaStreamAsync(streamInfo, fileName, progress);

                Console.WriteLine("Download complete!");
            }
            catch (Exception e)
            {
                Console.WriteLine("Error downloading {0}", e);
            }
        }
Exemplo n.º 19
0
        private static async Task MainAsync()
        {
            // Client
            var client = new YoutubeClient();

            // Get the video ID
            Console.Write("Enter Youtube video ID or URL: ");
            string id = Console.ReadLine();

            id = NormalizeId(id);

            // Get the video info
            Console.WriteLine("Loading...");
            var videoInfo = await client.GetVideoInfoAsync(id);

            Console.WriteLine('-'.Repeat(100));

            // Print metadata
            Console.WriteLine($"Id: {videoInfo.Id} | Title: {videoInfo.Title} | Author: {videoInfo.Author.Title}");

            // Get the most preferable stream
            Console.WriteLine("Looking for the best mixed stream...");
            var streamInfo = videoInfo.MixedStreams
                             .OrderBy(s => s.VideoQuality)
                             .Last();
            string normalizedFileSize = NormalizeFileSize(streamInfo.ContentLength);

            Console.WriteLine($"Quality: {streamInfo.VideoQualityLabel} | Container: {streamInfo.Container} | Size: {normalizedFileSize}");

            // Compose file name, based on metadata
            string fileExtension = streamInfo.Container.GetFileExtension();
            string fileName      = $"{videoInfo.Title}.{fileExtension}";

            // Remove illegal characters from file name
            fileName = fileName.Except(Path.GetInvalidFileNameChars());

            // Download video
            Console.WriteLine($"Downloading to [{fileName}]...");
            Console.WriteLine('-'.Repeat(100));

            var progress = new Progress <double>(p => Console.Title = $"YoutubeExplode Demo [{p:P0}]");
            await client.DownloadMediaStreamAsync(streamInfo, fileName, progress);

            Console.WriteLine("Download complete!");
            Console.ReadKey();
        }
Exemplo n.º 20
0
        public async Task YoutubeClient_DownloadClosedCaptionTrackAsync_Normal_Test()
        {
            var client    = new YoutubeClient();
            var videoInfo = await client.GetVideoInfoAsync("_QdPW8JrYzQ");

            var streamInfo = videoInfo.ClosedCaptionTracks.First();

            string outputFilePath = "DownloadClosedCaptionTrackAsync_Normal_Test_Output.bin";

            await client.DownloadClosedCaptionTrackAsync(streamInfo, outputFilePath);

            var fi = new FileInfo(outputFilePath);

            Assert.IsTrue(fi.Exists);
            Assert.AreNotEqual(0, fi.Length);
            fi.Delete();
        }
Exemplo n.º 21
0
        public async Task YoutubeClient_DownloadMediaStreamAsync_Normal_Test()
        {
            var client    = new YoutubeClient();
            var videoInfo = await client.GetVideoInfoAsync("_QdPW8JrYzQ");

            var streamInfo = videoInfo.AudioStreams.OrderBy(s => s.ContentLength).First();

            string outputFilePath = "DownloadMediaStreamAsync_Normal_Test_Output.bin";

            await client.DownloadMediaStreamAsync(streamInfo, outputFilePath);

            var fi = new FileInfo(outputFilePath);

            Assert.IsTrue(fi.Exists);
            Assert.AreNotEqual(0, fi.Length);
            fi.Delete();
        }
Exemplo n.º 22
0
        public async Task YoutubeClient_DownloadMediaStreamAsync_Test()
        {
            var id = (string)TestContext.DataRow["Id"];

            var client    = new YoutubeClient();
            var videoInfo = await client.GetVideoInfoAsync(id);

            var streamInfo     = videoInfo.AudioStreams.OrderBy(s => s.ContentLength).First();
            var outputFilePath = Path.Combine(Shared.TempDirectoryPath, Guid.NewGuid().ToString());

            Directory.CreateDirectory(Shared.TempDirectoryPath);
            await client.DownloadMediaStreamAsync(streamInfo, outputFilePath);

            var fileInfo = new FileInfo(outputFilePath);

            Assert.IsTrue(fileInfo.Exists);
            Assert.IsTrue(0 < fileInfo.Length);
        }
Exemplo n.º 23
0
        public async Task YoutubeClient_DownloadClosedCaptionTrackAsync_Test()
        {
            string id = (string)TestContext.DataRow["Id"];

            var client    = new YoutubeClient();
            var videoInfo = await client.GetVideoInfoAsync(id);

            var    streamInfo     = videoInfo.ClosedCaptionTracks.First();
            string outputFilePath = Path.Combine(Shared.TempDirectoryPath, Guid.NewGuid().ToString());

            Directory.CreateDirectory(Shared.TempDirectoryPath);
            await client.DownloadClosedCaptionTrackAsync(streamInfo, outputFilePath);

            var fileInfo = new FileInfo(outputFilePath);

            Assert.IsTrue(fileInfo.Exists);
            Assert.IsTrue(0 < fileInfo.Length);
        }
Exemplo n.º 24
0
        public static async Task <string> StreamUrl(Song Song)
        {
            if (Song.Type == SongType.YouTube)
            {
                YoutubeClient.TryParseVideoId(Song.Url, out string Id);

                var Client = new YoutubeClient();
                var Vid    = await Client.GetVideoInfoAsync(Id);

                MixedStreamInfo Max = null;
                foreach (var V in Vid.MixedStreams)
                {
                    if (Max == null || V.VideoQuality > Max.VideoQuality)
                    {
                        Max = V;
                    }
                }

                return(Max?.Url ?? string.Empty);
            }
            else if (Song.Type == SongType.SoundCloud)
            {
                var SCRes = await($"http://api.soundcloud.com/resolve?url={Song.Url}&{SC}").WebResponseRetryLoop();
                if (SCRes != string.Empty && SCRes.StartsWith("{\"kind\":\"track\""))
                {
                    var Parse = JObject.Parse(SCRes);

                    if (Parse["downloadable"] != null && (bool)Parse["downloadable"] == true)
                    {
                        return($"{Parse["download_url"]}?{SC}");
                    }

                    return($"{Parse["stream_url"]}?{SC}");
                }
            }
            else if (Song.Type == SongType.Telegram)
            {
                return(await GetTelegramUrl(Song.Url));
            }

            return(Song.Url);
        }
Exemplo n.º 25
0
        private async void button2_Click(object sender, EventArgs e)
        {
            YoutubeClient youtubeClient = new YoutubeClient();

            if (YoutubeClient.TryParseVideoId(tbLive.Text, out string videoId))
            {
                var videoInfo = await youtubeClient.GetVideoInfoAsync(videoId);

                HttpClient          httpClient = new HttpClient();
                HttpResponseMessage response   = await httpClient.GetAsync($"https://www.youtube.com/get_video_info?&video_id={videoId}&el=info&ps=default&eurl=&gl=US&hl=en");

                string raw = await response.Content.ReadAsStringAsync();

                // Parsing
                var dict = raw.Split('&')
                           .Select(p => p.Split('='))
                           .ToDictionary(p => p[0], p => p.Length > 1 ? Uri.UnescapeDataString(p[1]) : null);
                Console.WriteLine(dict["hlsvp"]);
            }
        }
Exemplo n.º 26
0
        public async Task SendAudio(IGuild g, IMessageChannel c, string input)
        {
            var yt = new YoutubeClient();

            if (input.ToLower().Contains("youtube.com"))
            {
                input = YoutubeClient.ParseVideoId(input);
            }
            else
            {
                var res = await yt.SearchAsync(input);

                input = res.FirstOrDefault();
            }

            var vInfo = await yt.GetVideoInfoAsync(input);

            var vStreams = vInfo.AudioStreams.OrderBy(x => x.Bitrate).Last();
            var vTitle   = vInfo.Title;

            FilePath = $@"{BasePath}{g.Id}/{vTitle}.{vStreams.Container.GetFileExtension()}";
            if (!Directory.Exists(BasePath + g.Id))
            {
                Directory.CreateDirectory(BasePath + g.Id);
            }

            if (!File.Exists(FilePath))
            {
                using (var goIn = await yt.GetMediaStreamAsync(vStreams))
                    using (var goOut = File.Create(FilePath))
                        await goIn.CopyToAsync(goOut);
            }

            if (ConnectedChannels.TryGetValue(g.Id, out IAudioClient _client))
            {
                var dStream = _client.CreatePCMStream(AudioApplication.Music);
                await CreateStream(FilePath, g.Id).StandardOutput.BaseStream.CopyToAsync(dStream);

                await dStream.FlushAsync();
            }
        }
Exemplo n.º 27
0
        public async Task YoutubeClient_GetMediaStreamAsync_CannotEmbed_Test()
        {
            var client    = new YoutubeClient();
            var videoInfo = await client.GetVideoInfoAsync("_kmeFXjjGfk");

            var streams = new List <MediaStreamInfo>();

            streams.AddRange(videoInfo.MixedStreams);
            streams.AddRange(videoInfo.AudioStreams);
            streams.AddRange(videoInfo.VideoStreams);

            foreach (var streamInfo in streams)
            {
                using (var stream = await client.GetMediaStreamAsync(streamInfo))
                {
                    Assert.That.IsSet(stream);

                    var buffer = new byte[100];
                    await stream.ReadAsync(buffer, 0, buffer.Length);
                }
            }
        }
Exemplo n.º 28
0
        public async Task PlaylistCmd([Remainder] string playlistLink)
        {
            var ytc = new YoutubeClient();

            var playListInfo = await ytc.GetPlaylistInfoAsync(YoutubeClient.ParsePlaylistId(playlistLink));

            var ten  = playListInfo.VideoIds.ToArray().Take(10).ToArray();
            var list = new List <string>();

            if (Queue.ContainsKey(Context.Guild.Id))
            {
                Queue.TryGetValue(Context.Guild.Id, out list);
            }
            await ReplyAsync($"Attempting to add the first 10 songs of **{playListInfo.Title}** to the queue!");

            var i = 0;

            foreach (var song in ten)
            {
                var videoInfo = await ytc.GetVideoInfoAsync(song);

                var title = videoInfo.Title;
                list.Add(title);
                await ReplyAsync($"`{i}` - **{title}** added to the queue");

                Queue.Remove(Context.Guild.Id);
                Queue.Add(Context.Guild.Id,
                          list); //ineffieient as f**k because im adding all songs one by one rather than as a group, however. it takes a long time so this is better timewise
                i++;
            }

            await PlayQueue();

            await ReplyAsync(
                $"**{playListInfo.Title}** has been added to the end of the queue. \nQueue Length: **{list.Count}**");
        }
Exemplo n.º 29
0
        public async Task YoutubeClient_GetMediaStreamAsync_Test()
        {
            string id = (string)TestContext.DataRow["Id"];

            var client    = new YoutubeClient();
            var videoInfo = await client.GetVideoInfoAsync(id);

            var streams = new List <MediaStreamInfo>();

            streams.AddRange(videoInfo.MixedStreams);
            streams.AddRange(videoInfo.AudioStreams);
            streams.AddRange(videoInfo.VideoStreams);

            foreach (var streamInfo in streams)
            {
                using (var stream = await client.GetMediaStreamAsync(streamInfo))
                {
                    Assert.That.IsSet(stream);

                    var buffer = new byte[100];
                    await stream.ReadAsync(buffer, 0, buffer.Length);
                }
            }
        }
Exemplo n.º 30
0
        public async Task SendAudioAsync(IGuild guild, IMessageChannel channel, string userInput)
        {
            var ytc = new YoutubeClient();

            if (userInput.ToLower().Contains("youtube.com") || userInput.ToLower().Contains("youtu.be"))
            {
                userInput = YoutubeClient.ParseVideoId(userInput);
            }
            else
            {
                var searchList = await ytc.SearchAsync(userInput);

                userInput = searchList.First();
            }

            var videoInfo = await ytc.GetVideoInfoAsync(userInput);


            var asi = videoInfo.AudioStreams.OrderBy(x => x.Bitrate).Last();


            var title = videoInfo.Title;

            var rgx = new Regex("[^a-zA-Z0-9 -]");

            title = rgx.Replace(title, "");

            var path = $@"C:\Users\jack\Documents\Visual Studio 2017\Projects\jackbot2.0\jackbot2.0\music\{guild.Id}\{title}.{asi.Container.GetFileExtension()}";
            await channel.SendMessageAsync("checking path");

            if (!Directory.Exists($@"C:\Users\jack\Documents\Visual Studio 2017\Projects\jackbot2.0\jackbot2.0\music\{guild.Id}"))
            {
                Directory.CreateDirectory($@"C:\Users\jack\Documents\Visual Studio 2017\Projects\jackbot2.0\jackbot2.0\music\{guild.Id}");
            }

            if (!File.Exists(path))
            {
                var embed = new EmbedBuilder()
                {
                    Title       = $"Attempting to download",
                    Description = $"{title}",
                    Color       = new Color(255, 0, 255)
                };



                await channel.SendMessageAsync($"", embed : embed.Build());

                using (var input = await ytc.GetMediaStreamAsync(asi))
                    using (var Out = File.Create(path))
                    {
                        await input.CopyToAsync(Out);
                    }
            }

            if (_connectedChannels.TryGetValue(guild.Id, out IAudioClient audioClient))
            {
                var embed = new EmbedBuilder()
                {
                    Title        = $"Now playing",
                    Description  = $"**{title}**\n**Duration**: {videoInfo.Duration}\n**Views**: {videoInfo.ViewCount}\n<:like:325971963078115328>{videoInfo.LikeCount} | <:dislike:325971963451408386> {videoInfo.DislikeCount}",
                    Color        = new Color(255, 0, 255),
                    ThumbnailUrl = videoInfo.ImageMaxResUrl
                };
                await channel.SendMessageAsync("", embed : embed.Build());

                var output        = CreateStream(path).StandardOutput.BaseStream;
                var discordStream = audioClient.CreatePCMStream(AudioApplication.Music, 94208, 2000);
                var Config        = GuildHandler.GuildConfigs[guild.Id];
                Config.musicid.name                 = title;
                Config.musicid.added                = DateTime.UtcNow;
                Config.musicid.duration             = videoInfo.Duration.ToString();
                Config.musicid.seconds              = videoInfo.Duration.TotalSeconds;
                Config.musicid.thumbnail            = $"https://img.youtube.com/vi/{videoInfo.Id}/maxresdefault.jpg";
                GuildHandler.GuildConfigs[guild.Id] = Config;
                await GuildHandler.SaveAsync(GuildHandler.GuildConfigs);

                await output.CopyToAsync(discordStream);

                await discordStream.FlushAsync();

                File.Delete(path);
            }
        }