예제 #1
0
        /// <summary>
        /// Get the dycrptet videos url
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task <List <YVideoInfo> > GetVideos(string id, int?formatCode = null)
        {
            try
            {
                var result        = new List <YVideoInfo>();
                var streamInfoSet = await dataContext.GetVideoMediaStreamInfosAsync(id);

                var video = await dataContext.GetVideoAsync(id);

                foreach (var item in streamInfoSet?.Muxed)
                {
                    if (formatCode.HasValue && formatCode.Value != item.Itag)
                    {
                        continue;
                    }
                    result.Add(new YVideoInfo()
                    {
                        FormatCode  = item.Itag,
                        Url         = item.Url,
                        Quality     = item.VideoQualityLabel,
                        Resolution  = item.Resolution.ToString(),
                        Size        = Actions.SizeSuffix(item.Size),
                        Duration    = video != null ? video.Duration.TotalHours >= 1 ? video.Duration.ToString("c") : string.Format("{0:mm}:{1:ss}", video.Duration, video.Duration) : "",
                        Description = video?.Description,
                        Auther      = video?.Author
                    });
                }
                return(result);
            }
            catch
            {
                return(null);
            }
        }
예제 #2
0
        public async void DownloadAsyncVideo(string url)
        {
            try
            {
                var id = YoutubeClient.ParseVideoId(url);

                var client        = new YoutubeClient();
                var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(id);

                var video = await client.GetVideoAsync(id);

                var mp4FileTitle = video.Title;

                var streamInfo = streamInfoSet.Muxed.FirstOrDefault(quality => quality.VideoQualityLabel == "360p");
                var ext        = streamInfo.Container.GetFileExtension();

                string mp4Path = Directory.GetCurrentDirectory() + "\\Download\\" + mp4FileTitle + "." + ext;

                await client.DownloadMediaStreamAsync(streamInfo, mp4Path);

                TagFile(url, mp4Path);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
예제 #3
0
        public async Task SendAudioAsync(IGuild guild, string songID)
        {
            Video vid = await ourYoutube.GetVideoAsync(songID);

            var stream = (await ourYoutube.GetVideoMediaStreamInfosAsync(songID)).Muxed.WithHighestVideoQuality();

            ToCopyFile = $@"{GuildAudioFiles}{guild.Id}/{vid.Id}.{stream.Container.GetFileExtension()}";
            if (!Directory.Exists($"{GuildAudioFiles}{guild.Id}"))
            {
                Directory.CreateDirectory($"{GuildAudioFiles}{guild.Id}");
            }

            if (!File.Exists(ToCopyFile))
            {
                await ourYoutube.DownloadMediaStreamAsync(stream, ToCopyFile);
            }

            if (ourGuilds.TryGetValue(guild.Id, out IAudioClient audio))
            {
                var discordStream = audio.CreatePCMStream(AudioApplication.Music);
                await CreateGuildStream(ToCopyFile, guild.Id).StandardOutput.BaseStream.CopyToAsync(discordStream);

                await discordStream.FlushAsync();
            }
        }
            private async Task <string> getVideoTitle(String videoId)
            {
                YoutubeClient client = new YoutubeClient();
                var           video  = await client.GetVideoAsync(videoId);

                return(video.Title);
            }
예제 #5
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);
            }
        }
예제 #6
0
        private async void MaterialFlatButton2_Click(object sender, EventArgs e)
        {
            var    client = new YoutubeClient();
            string link   = SearchBoxInput.Text;
            string id     = YoutubeClient.ParseVideoId(link);

            var video = await client.GetVideoAsync(id);

            var title     = video.Title;
            var author    = video.Author;
            var duration  = video.Duration;
            var desc      = video.Description;
            var thumbnail = video.Thumbnails.HighResUrl;
            var views     = video.Statistics.ViewCount;
            var likes     = video.Statistics.LikeCount;
            var dislikes  = video.Statistics.DislikeCount;
            var keywords  = video.Keywords;

            materialLabel1.Text  = title;
            materialLabel2.Text  = author;
            materialLabel3.Text  = duration.ToString();
            materialLabel7.Text  = views.ToString() + " views";
            textBox1.Text        = desc;
            pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
            pictureBox1.Load(thumbnail);
            textBox2.Text = "";
            foreach (string keyword in keywords)
            {
                textBox2.Text = textBox2.Text + keyword + ", ";
            }
            materialLabel4.Text = "Likes - " + likes + " Dislikes - " + dislikes;


            SaveThumbnailCheckBox.Show();
        }
예제 #7
0
        private async Task MainAsync()
        {
            clsBiblioteca biblioteca = new clsBiblioteca();
            //Nuevo Cliente de YouTube
            var client = new YoutubeClient();
            //Lee la URL de youtube que le escribimos en el textbox.
            var videoId = NormalizeVideoId(txtURL.Text);
            var video   = await client.GetVideoAsync(videoId);

            var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(videoId);

            //Busca la mejor resolución en la que está disponible el video.
            var streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality();
            //Compone el nombre que tendrá el video en base a su título y extensión.
            var fileExtension = streamInfo.Container.GetFileExtension();
            var fileName      = $"{video.Title}.{fileExtension}";

            //TODO: Reemplazar los caractéres ilegales del nombre
            //fileName = RemoveIllegalFileNameChars(fileName);
            //Activa el timer para que el proceso funcione de forma asincrona
            ckbAudio.Enabled = true;
            // mensajes indicando que el video se está descargando
            label4.Text = "Descargando el video...";
            //TODO: se pude usar una barra de progreso para ver el avance
            //using (var progress = new ProgressBar());
            //Empieza la descarga.
            await client.DownloadMediaStreamAsync(streamInfo, fileName);

            //Ya descargado se inicia la conversión a MP3
            var Convert = new NReco.VideoConverter.FFMpegConverter();
            //Especificar la carpeta donde se van a guardar los archivos, recordar la \ del final
            String SaveMP3File = @"C:\Users\Ramirez\Documents\Visual Studio 2015\Projects\ProyectoFinal3\ProyectoFinal3\mp3" + fileName.Replace(".mp4", ".mp3");

            biblioteca.Url     = SaveMP3File;
            biblioteca.Cancion = fileName;
            //Guarda el archivo convertido en la ubicación indicada
            Convert.ConvertMedia(fileName, SaveMP3File, "mp3");
            //Si el checkbox de solo audio está chequeado, borrar el mp4 despues de la conversión
            if (ckbAudio.Checked)
            {
                File.Delete(fileName);
            }
            //Indicar que se terminó la conversion
            MessageBox.Show("Vídeo convertido correctamente.");
            label4.Text      = "";
            txtURL.Text      = "";
            ckbAudio.Enabled = false;

            biblioteca.Letra   = URlLyries;
            biblioteca.Portada = URLportada;
            biblioteca.Id      = contador.ToString();
            GuardarBiblioteca(biblioteca);
            // GuardarCancion(biblioteca);
            //TODO: Cargar el MP3 al reproductor o a la lista de reproducción
            //CargarMP3s();
            //Se puede incluir un checkbox para indicar que de una vez se reproduzca el MP3
            //if (ckbAutoPlay.Checked)
            //  ReproducirMP3(SaveMP3File);
            return;
        }
예제 #8
0
        //async public Task DownloadPlaylist(string playListId)
        //{
        //    var playlist = await client.GetPlaylistAsync(playListId);
        //    foreach (var video in playlist.Videos)
        //    {
        //        await DownloadVideo(video.Id, $@"F:\Videos\Youtube\{channelInfo.Title}");
        //    }
        //}

        async public Task DownloadVideo(string videoId, string folder)
        {
            try
            {
                var video = await client.GetVideoAsync(videoId);

                var title    = video.Title.CleanFileName();
                var author   = video.Author.CleanFileName();
                var duration = video.Duration;
                var date     = video.UploadDate;

                // Get metadata for all streams in this video
                var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(videoId);

                // ...or highest quality & highest framerate MP4 video stream
                var streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality();

                // Get file extension based on stream's container
                var ext = streamInfo.Container.GetFileExtension();

                var videoName = $"{folder}\\{author}-{date.ToString("yyyyMMddHH")}-{title}.[{video.Id}].{ext}";
                // Download stream to file
                var progress = new MyProgress(videoName);
                await client.DownloadMediaStreamAsync(streamInfo, videoName, progress);

                progress.Dispose();
            }
            catch (Exception e)
            {
                Console.Write(e.Message);
            }
            //client.DownloadMediaStreamAsync()
        }
예제 #9
0
        /*public bool GetVideoThumbnail(string path, string saveThumbnailTo, int seconds)
         * {
         *  string parameters = $"-ss {seconds} -i {path} -f image2 -vframes 1 -y {saveThumbnailTo}";
         *
         *  var processInfo = new ProcessStartInfo();
         *  processInfo.FileName = pathToConvertor;
         *  processInfo.Arguments = parameters;
         *  processInfo.CreateNoWindow = true;
         *  processInfo.UseShellExecute = false;
         *
         *  File.Delete(saveThumbnailTo);
         *
         *  using (var process = new Process())
         *  {
         *      process.StartInfo = processInfo;
         *      process.Start();
         *      process.WaitForExit();
         *  }
         *
         *  return File.Exists(saveThumbnailTo);
         * }*/

        private static void Test()
        {
            var client = new YoutubeClient();

            client.GetChannelUploadsAsync("UCZqh6VE-OYFz2RCWDbZQOqw").ContinueWith(task =>
            {
                var video = task.Result.FirstOrDefault(v => v.Title.Contains("listening practice test"));

                client.GetVideoAsync("").ContinueWith(t =>
                {
                    //t.Result.
                    //t.Result.
                });

                client.GetVideoClosedCaptionTrackInfosAsync(video.Id).ContinueWith(task1 =>
                {
                    //task1.Result[0].
                    var captionTrackInfo = task1.Result.FirstOrDefault(info => info.Language.Code == "en");
                    client.GetClosedCaptionTrackAsync(captionTrackInfo).ContinueWith(task2 =>
                    {
                        var captionTrack = task2.Result;
                        foreach (var captionTrackCaption in captionTrack.Captions)
                        {
                            Console.WriteLine($"{captionTrackCaption.Offset}: {captionTrackCaption.Text}");
                        }
                    });
                });
            });
        }
예제 #10
0
        private async void downloadMethod(object sender)
        {
            Instruction = "Downloading ...";
            var id     = YoutubeClient.ParseVideoId(Link);
            var client = new YoutubeClient();
            var video  = await client.GetVideoAsync(id);

            var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(id);

            var streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality();

            //var ext = streamInfo.Container.GetFileExtension();
            Title = video.Title.Replace("/", "").Replace("\\", "");
            string videoPath      = "D:\\" + Title + ".mp4";
            string audioPath      = "D:\\" + Title + ".mp3";
            string outputFilePath = Title + ".avi";

            await client.DownloadMediaStreamAsync(streamInfo, videoPath);

            var streamInfo2 = streamInfoSet.Audio.WithHighestBitrate();
            await client.DownloadMediaStreamAsync(streamInfo2, audioPath);

            // Not working ffmpeg due to lack of version support => Can't yet to merge video and audio together
            //var ffmpeg = new FFMpegConverter();
            //var ffmpegPath = ffmpeg.FFMpegToolPath + ffmpeg.FFMpegExeName;
            //Process.Start(new ProcessStartInfo
            //{
            //    FileName = ffmpegPath,
            //    Arguments = $"-i {videoPath} -i {audioPath} -c:v copy -c:a aac -strict experimental {outputFilePath}"
            //}).WaitForExit();

            Instruction = "Done!";
        }
예제 #11
0
        protected (Video Video, MediaStreamInfo StreamInfo) GetVideoData(string videoId, YoutubeClient client, bool isOutputMp3)
        {
            if (!YoutubeClient.ValidateVideoId(videoId))
            {
                throw new ArgumentException("Invalid video id");
            }

            var streamInfoSet = client.GetVideoMediaStreamInfosAsync(videoId).GetAwaiter().GetResult();

            MediaStreamInfo streamInfo;

            if (isOutputMp3)
            {
                streamInfo = streamInfoSet.Audio.WithHighestBitrate();
            }
            else
            {
                streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality();
            }

            var video = client.GetVideoAsync(videoId)
                        .GetAwaiter()
                        .GetResult();

            return(video, streamInfo);
        }
예제 #12
0
        public void RunYoutubeDetailPipeline(string urlField, string detailField, string videoField, string streamField, string captionField)
        {
            var     it       = this.Data;
            JObject obj      = JObject.FromObject(it);
            var     urlVideo = obj[urlField].ToString();

            var client = new YoutubeClient();
            var id     = YoutubeClient.ParseVideoId(urlVideo); // "bnsUkE8i0tU"

            obj[detailField] = new JObject();
            if (!string.IsNullOrEmpty(videoField))
            {
                var video = client.GetVideoAsync(id).Result;
                var json1 = JsonConvert.SerializeObject(video, new StringEnumConverter());
                obj[detailField][videoField] = JObject.Parse(json1);
            }

            if (!string.IsNullOrEmpty(streamField))
            {
                var streamInfoSet = client.GetVideoMediaStreamInfosAsync(id).Result;
                var json2         = JsonConvert.SerializeObject(streamInfoSet, new StringEnumConverter());
                obj[detailField][streamField] = JObject.Parse(json2);
            }

            if (!string.IsNullOrEmpty(captionField))
            {
                var caption = client.GetVideoClosedCaptionTrackInfosAsync(id).Result;
                var json3   = JsonConvert.SerializeObject(caption, new StringEnumConverter());
                obj[detailField][captionField] = JArray.Parse(json3);
            }
        }
예제 #13
0
        public async Task GetPlayList()
        {
            int           location = 1;
            string        respone  = "";
            Video         TempHolder;
            YoutubeClient client = new YoutubeClient();

            if (PlayList.Count > 0)
            {
                for (int i = 0; i < PlayList.Count; i++)
                {
                    respone += (location) + ": " + PlayList.ToArray()[i].title + "\n";
                    location++;
                }
                if (PreQueue.Count > 0)
                {
                    for (int x = 0; x < PreQueue.Count; x++)
                    {
                        TempHolder = await client.GetVideoAsync(YoutubeClient.ParseVideoId(PreQueue.ToArray()[x]));

                        respone += (location) + ": " + TempHolder.Title + "\n";
                        location++;
                    }
                }
                await Context.Channel.SendMessageAsync(respone);
            }
            else
            {
                await ReplyAsync("Error no songs in playlist");
            }
        }
        public static async Task DownloadYouTubeVideoAsync(string youTubeVideoId, string destinationFolder, CancellationToken token)
        {
            YoutubeClient client    = new YoutubeClient();
            var           videoInfo = await client.GetVideoAsync(youTubeVideoId);

            var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(youTubeVideoId);

            MuxedStreamInfo streamInfo = null;

            if (Settings.Instance.PreferredQuality != "Highest")
            {
                streamInfo = streamInfoSet.Muxed.Where(p => p.VideoQualityLabel == Settings.Instance.PreferredQuality).FirstOrDefault();
            }

            if (Settings.Instance.PreferredQuality == "Highest" || streamInfo == null)
            {
                streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality();
            }

            string fileExtension = streamInfo.Container.GetFileExtension();
            string fileName      = "[" + videoInfo.Author + "] " + videoInfo.Title + "." + fileExtension;

            //Remove invalid characters from filename
            string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
            Regex  r           = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));

            fileName = r.Replace(fileName, "");

            await client.DownloadMediaStreamAsync(streamInfo, Path.Combine(destinationFolder, fileName), cancellationToken : token);
        }
        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}]");
        }
예제 #16
0
파일: Program.cs 프로젝트: talanc/PodCloud
        static async Task <int> RunInfo(InfoVerb verb)
        {
            foreach (var source in verb.Source)
            {
                if (YoutubeClient.ValidateChannelId(source))
                {
                    var channel = await youtube.GetChannelAsync(source);

                    Console.WriteLine(channel.Title);

                    var uploads = await youtube.GetChannelUploadsAsync(source, 1);

                    for (var i = 0; i < Math.Min(3, uploads.Count); i++)
                    {
                        var upload = uploads[i];
                        Console.WriteLine($"- {upload.Title} (id: {upload.Id}, date: {upload.UploadDate.Date.ToShortDateString()}, duration: {upload.Duration})");
                    }
                }
                else if (YoutubeClient.ValidateVideoId(source))
                {
                    var video = await youtube.GetVideoAsync(source);

                    Console.WriteLine(video.Title);
                }
            }

            return(0);
        }
예제 #17
0
        public async Task <ActionResult> GetPlaylist(string channel)
        {
            var model = new List <PlayListItem>();

            ViewBag.channel = channel;
            try
            {
                var user = ContextService.GetUserFromChannelname(channel);
                var bcs  = ContextService.GetBotChannelSettings(user);
                var bus  = ContextService.GetBotUserSettingsForUser(user);

                var channelMeta = await Api.V5.Channels.GetChannelAsync(bus.ChannelToken);

                ViewBag.ChannelProfileBannerUrl = channelMeta.ProfileBanner;
                ViewBag.ChannelLogo             = channelMeta.Logo;
                var songRequests   = bcs.SongRequests.Where(s => s.Deleted == false);
                var songThumbnails = new List <string>();
                var client         = new YoutubeClient();
                foreach (var song in songRequests)
                {
                    var video = await client.GetVideoAsync(song.VideoId);

                    songThumbnails.Add(video.Thumbnails.LowResUrl);
                }

                ViewBag.Thumbnails = songThumbnails;
                return(View(songRequests));
            }
            catch (Exception e)
            {
                ViewBag.Error = e.Message;
                return(View(model));
            }
        }
예제 #18
0
        public async Task YTvid(string url)
        {
            var id     = YoutubeClient.ParseVideoId(url); // "bnsUkE8i0tU"
            var client = new YoutubeClient();

            var video = await client.GetVideoAsync(id);

            var title    = video.Title;    // "Infected Mushroom - Spitfire [Monstercat Release]"
            var author   = video.Author;   // "Monstercat"
            var duration = video.Duration; // 00:07:14

            var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(id);

            // Select one of the streams, e.g. highest quality muxed stream
            var streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality();

            var ext = streamInfo.Container.GetFileExtension();

            // Download stream to file
            char[] invalidFileNameChars = Path.GetInvalidFileNameChars();
            var    validFilename        = new string(title.Where(ch => !invalidFileNameChars.Contains(ch)).ToArray());
            await client.DownloadMediaStreamAsync(streamInfo, @"D:\nBot\Videos\" + validFilename + "." + ext);

            //string inputFile = @"D:\"+ validFilename + "."+ext,outputFile = @"D:\" + validFilename + ".mp3";

            //var convert =  new FFMpeg() .ExtractAudio(FFMpegSharp.VideoInfo.FromPath(inputFile),new FileInfo(outputFile));
        }
예제 #19
0
        //public async Task<IActionResult> Download(string url = null, FormatoDescarga format = FormatoDescarga.mp3, TimeSpan? TiempoInicio = null, TimeSpan? TiempoFin = null)
        public async Task <IActionResult> Download(string url = null, FormatoDescarga format = FormatoDescarga.mp3)
        {
            var youtubeDL  = new YoutubeDL();
            var metaClient = new YoutubeClient();

            string mediaUrl      = WebUtility.UrlDecode(url);
            var    mediaMetadata = await metaClient.GetVideoAsync(YoutubeClient.ParseVideoId(mediaUrl));

            Task <string> fileTask = null;

            switch (format)
            {
            case FormatoDescarga.mp3:
                fileTask = Utils.DownloadMP3Async(mediaUrl);
                break;

            case FormatoDescarga.mp4:
                fileTask = Utils.DownloadMP4Async(mediaUrl);
                break;
            }
            MemoryStream media = new MemoryStream(System.IO.File.ReadAllBytes(fileTask.Result));

            media.Seek(0, SeekOrigin.Begin);
            System.IO.File.Delete(fileTask.Result);
            return(new FileStreamResult(media, "application/octet-stream")
            {
                FileDownloadName = (mediaMetadata.Title + Path.GetExtension(fileTask.Result))
            });
        }
예제 #20
0
        public async Task start_downloadAsync(string id)
        {
            var client = new YoutubeClient();

            var video = await client.GetVideoAsync(id);

            UrlParser parser = new UrlParser(video.Title);
            string    path   = (string)Properties.Settings.Default[setting];

            try
            {
                // Get metadata for all streams in this video
                var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(id);

                // ...or highest bitrate audio stream
                var streamInfo = streamInfoSet.Audio.WithHighestBitrate();

                // Get file extension based on stream's container
                var ext = streamInfo.Container.GetFileExtension();

                await client.DownloadMediaStreamAsync(streamInfo,
                                                      $"{path}//{parser.getUrl()}.mp3");

                download = new Download("", video.Title, video.Author, video.Duration.ToString());
            }
            catch (Exception exc)
            {
                download = new Download(exc.Message, "", "", "");
            }
        }
예제 #21
0
        public async Task PobierzAsync()
        {
            try
            {
                var client = new YoutubeClient();
                var url    = textBox1.Text;
                var id     = YoutubeClient.ParsePlaylistId(url);

                var playlist = await client.GetPlaylistAsync(id);

                foreach (var vid in playlist.Videos)
                {
                    var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(vid.Id);

                    var streamInfo = streamInfoSet.Audio.WithHighestBitrate();
                    var ext        = streamInfo.Container.GetFileExtension();
                    var video      = await client.GetVideoAsync(vid.Id);

                    string sourcePath = $"C:/YTMP3/{video.Title}.{ext}";
                    string outputPath = $"C:/YTMP3/{video.Title}.mp3";
                    await client.DownloadMediaStreamAsync(streamInfo, sourcePath);

                    var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
                    ffMpeg.ConvertMedia(sourcePath, outputPath, Format.mp4);

                    File.Delete(sourcePath);
                }
                MessageBox.Show("Pobrałem.");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Coś poszło nie tak." + Environment.NewLine + ex.Message);
            }
        }
예제 #22
0
        public DownloadItem(DownloadHistory history)
        {
            //When a new instance of DownloadItem is created with this constructor, it is being used to show it as history. There will not be a download button
            InitializeComponent();
            isHistory     = true;
            historyRecord = history;



            new Thread(async() =>
            {
                try
                {
                    //Because for some reason assigning 5 to a property that already is 5 makes it work. ? It doesn't show the elipse radius without this.
                    bunifuElipse1.ElipseRadius = 5;

                    pbYoutubeThumbnail.Load(history.ThumbnailLink);
                    theVideo = await client.GetVideoAsync(history.VideoId);
                }
                catch { }
            }).Start();



            lblStatus.Location  = pbLoad.Location;
            lblStatus.Text      = history.DownloadDate;
            btnDownload.Enabled = true;
            pbLoad.Visible      = false;
            lblExit.Enabled     = true;
            string completeString = "";
            string subAuthor      = "";
            string subTitle       = "";

            if (history.Title.Length > 33)
            {
                subTitle        = history.Title.Substring(0, 33) + "...";
                completeString += subTitle + "   ";
            }
            else
            {
                completeString += history.Title + "   ";
            }


            if (history.ChannelTitle.Length > 23)
            {
                subAuthor       = history.ChannelTitle.Substring(0, 23) + "...";
                completeString += subAuthor + "   ";
            }
            else
            {
                completeString += history.ChannelTitle + "   ";
            }



            completeString += history.Duration;
            lblTitle.Text   = completeString;
        }
예제 #23
0
        //el async permite que sea un proceso asincrono, es decir que el proceso de conversión siga corriendo
        //independientemente de los demás procesos, y que no parezca que el programa se congeló
        private async void button1_ClickAsync(object sender, EventArgs e)
        {
            //nuevo cliente de Youtube
            var client = new YoutubeClient();
            //lee la dirección de youtube que le escribimos en el textbox
            var videoId = NormalizeVideoId(txtURL.Text);
            var video   = await client.GetVideoAsync(videoId);

            var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(videoId);

            // Busca la mejor resolución en la que está disponible el video
            var streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality();

            // Compone el nombre que tendrá el video en base a su título y extensión
            var fileExtension = streamInfo.Container.GetFileExtension();
            var fileName      = $"{video.Title}.{fileExtension}";

            //TODO: Reemplazar los caractéres ilegales del nombre
            //fileName = RemoveIllegalFileNameChars(fileName);

            //Activa el timer para que el proceso funcione de forma asincrona
            tmrVideo.Enabled = true;

            // mensajes indicando que el video se está descargando
            txtMensaje.Text = "Descargando el video ... ";

            //TODO: se pude usar una barra de progreso para ver el avance
            //using (var progress = new ProgressBar())

            //Empieza la descarga
            await client.DownloadMediaStreamAsync(streamInfo, fileName);

            //Ya descargado se inicia la conversión a MP3
            var Convert = new NReco.VideoConverter.FFMpegConverter();
            //Especificar la carpeta donde se van a guardar los archivos, recordar la \ del final
            String SaveMP3File = @"E:\MP3\" + fileName.Replace(".mp4", ".mp3");

            //Guarda el archivo convertido en la ubicación indicada
            Convert.ConvertMedia(fileName, SaveMP3File, "mp3");

            //Si el checkbox de solo audio está chequeado, borrar el mp4 despues de la conversión
            if (ckbAudio.Checked)
            {
                File.Delete(fileName);
            }


            //Indicar que se terminó la conversion
            txtMensaje.Text      = "Archivo Convertido en MP3";
            tmrVideo.Enabled     = false;
            txtMensaje.BackColor = Color.White;

            //TODO: Cargar el MP3 al reproductor o a la lista de reproducción
            //CargarMP3s();
            //Se puede incluir un checkbox para indicar que de una vez se reproduzca el MP3
            //if (ckbAutoPlay.Checked)
            //  ReproducirMP3(SaveMP3File);
            return;
        }
예제 #24
0
        public async Task <IActionResult> GetMetadata(string url)
        {
            var client = new YoutubeClient();
            var id     = YoutubeClient.ParseVideoId(WebUtility.UrlDecode(url));
            var video  = await client.GetVideoAsync(id);

            return(Ok(video));
        }
예제 #25
0
        public async Task YoutubeClient_GetVideoAsync_Test(string videoId)
        {
            var client = new YoutubeClient();

            var video = await client.GetVideoAsync(videoId);

            Assert.That(video.Id, Is.EqualTo(videoId));
        }
예제 #26
0
        /// <summary>
        /// Get the web video async
        /// </summary>
        /// <param name="videoUrl"></param>
        /// <returns>return a <see cref="Task{TResult}"/></returns>
        public static async Task <Video> GetVideoAsync(string videoUrl)
        {
            var id     = YoutubeClient.ParseVideoId(videoUrl);
            var client = new YoutubeClient();
            var result = await client.GetVideoAsync(id);

            return(result);
        }
        private async void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                if (YoutubeClient.TryParsePlaylistId(PlaylistLinkTextBox.Text, out string playlistId))
                {
                    _ = Task.Run(async() =>
                    {
                        list = await client.GetPlaylistAsync(playlistId).ConfigureAwait(false);
                        VideoList.Clear();
                        await UpdatePlaylistInfo(Visibility.Visible, list.Title, list.Author, list.Statistics.ViewCount.ToString(), list.Videos.Count.ToString(), $"https://img.youtube.com/vi/{list?.Videos?.FirstOrDefault()?.Id}/0.jpg", true, true);
                    }).ConfigureAwait(false);
                }
                else if (YoutubeClient.TryParseChannelId(PlaylistLinkTextBox.Text, out string channelId))
                {
                    _ = Task.Run(async() =>
                    {
                        channel = await client.GetChannelAsync(channelId).ConfigureAwait(false);
                        list    = await client.GetPlaylistAsync(channel.GetChannelVideosPlaylistId());
                        VideoList.Clear();
                        await UpdatePlaylistInfo(Visibility.Visible, channel.Title, list.Author, list.Statistics.ViewCount.ToString(), list.Videos.Count.ToString(), channel.LogoUrl, true, true);
                    }).ConfigureAwait(false);
                }
                else if (YoutubeClient.TryParseUsername(PlaylistLinkTextBox.Text, out string username))
                {
                    _ = Task.Run(async() =>
                    {
                        string channelID = await client.GetChannelIdAsync(username).ConfigureAwait(false);
                        var channel      = await client.GetChannelAsync(channelID).ConfigureAwait(false);
                        list             = await client.GetPlaylistAsync(channel.GetChannelVideosPlaylistId()).ConfigureAwait(false);
                        VideoList.Clear();
                        await UpdatePlaylistInfo(Visibility.Visible, channel.Title, list.Author, list.Statistics.ViewCount.ToString(), list.Videos.Count.ToString(), channel.LogoUrl, true, true);
                    }).ConfigureAwait(false);
                }
                else if (YoutubeClient.TryParseVideoId(PlaylistLinkTextBox.Text, out string videoId))
                {
                    _ = Task.Run(async() =>
                    {
                        var video = await client.GetVideoAsync(videoId);
                        VideoList.Clear();
                        VideoList.Add(video);
                        list = null;
                        await UpdatePlaylistInfo(Visibility.Visible, video.Title, video.Author, video.Statistics.ViewCount.ToString(), string.Empty, $"https://img.youtube.com/vi/{video.Id}/0.jpg", true, false);
                    }).ConfigureAwait(false);
                }
                else
                {
                    await UpdatePlaylistInfo().ConfigureAwait(false);
                }
            }

            catch (Exception ex)
            {
                await GlobalConsts.Log(ex.ToString(), "MainPage TextBox_TextChanged");

                await GlobalConsts.ShowMessage((string)FindResource("Error"), ex.Message);
            }
        }
예제 #28
0
        public async void Run(IScsServerClient client, List <string> parameters, string messageId)
        {
            var sender = new ServerSender(client);
            var dj     = JsonConvert.DeserializeObject <Dj>(parameters[0]);

            if (!Utils.Instance.IsActiveLogin(client) || dj.Track.Count <= 0)
            {
                sender.Error(messageId);
            }

            foreach (var track in dj.Track)
            {
                if (!YoutubeClient.ValidateVideoId(track.Id))
                {
                    sender.Error(messageId);
                    return;
                }
            }

            var userClient = DataSingleton.Instance.ServerClients[(int)client.ClientId].ToUserClient();

            //TODO to change if want to have multichannel watchning feature
            var room = DataSingleton.Instance.Rooms.GetAllItems()
                       .FirstOrDefault(x => x.InsideInfo.Clients.Exists(
                                           y => y.Id == userClient.Id));

            if (room == null)
            {
                sender.Error(messageId);
                return;
            }

            var yt = new YoutubeClient();

            foreach (var track in dj.Track)
            {
                var query = await yt.GetVideoAsync(track.Id);

                track.Time = Convert.ToInt32(query.Duration.TotalSeconds);
            }

            room.InsideInfo.Djs.Add(dj);
            sender.Success(messageId);

            if (room.InsideInfo?.Clients != null)
            {
                foreach (var roomUser in room.InsideInfo?.Clients)
                {
                    var roomClient = DataSingleton.Instance.ServerClients.GetAllItems()
                                     .FirstOrDefault(x => x.Id == roomUser.Id)
                                     ?.Client;

                    sender = new ServerSender(roomClient);
                    sender.NewDjInQueue(dj);
                }
            }
        }
예제 #29
0
        private async Task GetVideoInfoAsync(string id)
        {
            var client = new YoutubeClient();
            var video  = await client.GetVideoAsync(id);

            var title    = video.Title;    // "Infected Mushroom - Spitfire [Monstercat Release]"
            var author   = video.Author;   // "Monstercat"
            var duration = video.Duration; // 00:07:14
        }
예제 #30
0
        private static async Task MainAsync()
        {
            // Client
            var client = new YoutubeClient();

            // Get the video ID
            Console.Write("Enter YouTube video ID or URL: ");
            var videoId = Console.ReadLine();

            videoId = NormalizeVideoId(videoId);
            Console.WriteLine();

            // Get the video info
            Console.Write("Obtaining general video info... ");
            var video = await client.GetVideoAsync(videoId);

            Console.WriteLine('✓');
            Console.WriteLine($"> {video.Title} by {video.Author}");
            Console.WriteLine();

            // Get media stream info set
            Console.Write("Obtaining media stream info set... ");
            var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(videoId);

            Console.WriteLine('✓');
            Console.WriteLine("> " +
                              $"{streamInfoSet.Muxed.Count} muxed streams, " +
                              $"{streamInfoSet.Video.Count} video-only streams, " +
                              $"{streamInfoSet.Audio.Count} audio-only streams");
            Console.WriteLine();

            // Get the best muxed stream
            var streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality();

            Console.WriteLine("Selected muxed stream with highest video quality:");
            Console.WriteLine("> " +
                              $"{streamInfo.VideoQualityLabel} video quality | " +
                              $"{streamInfo.Container} format | " +
                              $"{NormalizeFileSize(streamInfo.Size)}");
            Console.WriteLine();

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

            // Replace illegal characters in file name
            fileName = fileName.Replace(Path.GetInvalidFileNameChars(), '_');

            // Download video
            Console.Write("Downloading... ");
            using (var progress = new ProgressBar())
                await client.DownloadMediaStreamAsync(streamInfo, fileName, progress);
            Console.WriteLine();

            Console.WriteLine($"Video saved to '{fileName}'");
            Console.ReadKey();
        }