Exemplo n.º 1
0
        public static async void GetVideo(string fileLocation,
                                          string address, NSButton videoCheckBox,
                                          NSButton audioCheckBox)
        {
            var client = new YoutubeClient();
            var id     = YoutubeClient.ParseVideoId(address);

            var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(id);

            if (videoCheckBox.State == NSCellStateValue.On)
            {
                var streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality();
                var ext        = streamInfo.Container.GetFileExtension();
                await client.DownloadMediaStreamAsync(streamInfo, fileLocation + "." + ext);
            }

            if (audioCheckBox.State == NSCellStateValue.On)
            {
                var audioStream = streamInfoSet.Audio.WithHighestBitrate();
                var ext         = audioStream.Container.GetFileExtension();
                var tempName    = Guid.NewGuid().ToString("n").Substring(0, 8) + "." + ext;
                await client.DownloadMediaStreamAsync(audioStream, "/tmp/" + tempName);

                var cmdArgs = "-i " + "/tmp/" + tempName + " -acodec alac " +
                              fileLocation + ".m4a";
                Process ffmpeg = new Process();
                ffmpeg.StartInfo.UseShellExecute = true;
                ffmpeg.StartInfo.FileName        = "ffmpeg";
                ffmpeg.StartInfo.Arguments       = cmdArgs;
                ffmpeg.StartInfo.CreateNoWindow  = true;
                ffmpeg.Start();
            }
        }
Exemplo n.º 2
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!";
        }
Exemplo n.º 3
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());
            }
        }
Exemplo n.º 4
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();
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Downloads the requested song to the "Downloads" folder, if it hasn't already been downloaded.
        /// </summary>
        /// <returns>Boolean representing if the download was successful.</returns>
        public async Task <bool> DownloadAsync()
        {
            if (IsDownloaded)
            {
                return(IsDownloaded);
            }
            if (Video == null)
            {
                return(false);
            }

            var fileName = ToSafeFileName(Video.Title);
            var path     = APP_DIRECTORY + "downloads\\" + fileName;

            var mediaStreamInfos = await youtubeClient.GetVideoMediaStreamInfosAsync(Video.Id);

            var streamInfo = mediaStreamInfos.Audio.Where(x => x.Container != Container.WebM).First();
            var extension  = streamInfo.Container.GetFileExtension();

            if (File.Exists(path))
            {
                FilePath     = $"{path}.{extension}";
                IsDownloaded = true;
                return(true);
            }

            await youtubeClient.DownloadMediaStreamAsync(streamInfo, $"{path}.{extension}");

            FilePath     = $"{path}.{extension}";
            IsDownloaded = true;
            return(true);
        }
Exemplo n.º 6
0
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            string path = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, /*$"DownloadedSongs/{video.Title}.mp3"*/ @"DownloadedSongs");

            try
            {
                await client.DownloadMediaStreamAsync(audioStreamInfo, $"DownloadedSongs/{video.Title}.webm");

                FFMpegConverter converter = new FFMpegConverter();
                converter.ConvertMedia($"DownloadedSongs/{video.Title}.webm", $"DownloadedSongs/{video.Title}.mp3", "mp3");

                TryExtractArtistAndTitle(video.Title, out var artist, out var title);

                var taggedFile = TagLib.File.Create($"DownloadedSongs/{video.Title}.mp3");
                Debug.WriteLine("DURATION : " + taggedFile.Properties.Duration);
                taggedFile.Tag.Performers = new[] { artist };
                taggedFile.Tag.Title      = title;
                taggedFile.Tag.Album      = "Downloaded from Youtube";
                taggedFile.Tag.Pictures   = picture != null ? new[] { picture } : Array.Empty <IPicture>();
                taggedFile.Save();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            this.DialogResult = true;
        }
Exemplo n.º 7
0
        public async Task <string> DownloadAudioNative(string folderPath, string fileName = "")
        {
            var client = new YoutubeClient();

            if (StreamInfoSet == null)
            {
                StreamInfoSet = await client.GetVideoMediaStreamInfosAsync(videoID); // Get metadata for all streams in this video
            }
            // Select one of the streams, e.g. highest quality muxed stream
            var streamInfo = this.StreamInfoSet.Audio.WithHighestBitrate();

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

            if (fileName == "")
            {
                fileName = this.Video.Title; //set filename to the video title if not specified
            }
            fileName = $"{fileName}.{ext}";  //add the extension to the filename
            string filePath = Path.Combine(folderPath, fileName);

            filePath = MusicTagging.ReplaceInvalidChars(filePath);         //replace any invalid chars in filePath with valid
            filePath = MusicTagging.UpdateFileNameForDuplicates(filePath); //add "copy" to filename if file exists

            var fs = File.Create(filePath);
            await client.DownloadMediaStreamAsync(streamInfo, fs); //wait for the download to finish

            fs.Close();

            return(filePath);
        }
Exemplo n.º 8
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);

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

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

            if (streamInfo == null)
            {
                Console.WriteLine("This videos has no streams");
                return;
            }

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

            // Download video
            Console.Write($"Downloading stream: {streamInfo.VideoQualityLabel} / {fileExtension}... ");
            using (var progress = new InlineProgress())
                await client.DownloadMediaStreamAsync(streamInfo, fileName, progress);

            Console.WriteLine($"Video saved to '{fileName}'");
        }
        private async void worker_DoWorkAsync(object sender, DoWorkEventArgs e)
        {
            loadingControl.Dispatcher.Invoke(new Action(() =>
            {
                loadingControl.LoadingStateText.Text = "Get Downloading Urls ... ";
            }));

            loadingControl.Dispatcher.Invoke(new Action(() =>
            {
                loadingControl.loadingTextBlock.Text = " 0%";
            }));

            string link = url;
            var    id   = YoutubeClient.ParseVideoId(url);

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

            var streamInfo = streamInfoSet.Video
                             .Where(s => s.Container == YoutubeExplode.Models.MediaStreams.Container.Mp4)
                             .OrderByDescending(s => s.VideoQuality)
                             .ThenByDescending(s => s.Framerate)
                             .First();

            var ext = streamInfo.Container.GetFileExtension();

            await client.DownloadMediaStreamAsync(streamInfo, $"downloaded_video.{ext}");

            worker.ReportProgress(100);
        }
Exemplo n.º 10
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));
        }
Exemplo n.º 11
0
        /// <summary>
        /// Downloads the requested song to the "Downloads" folder, if it hasn't already been downloaded.
        /// </summary>
        /// <returns>Boolean representing if the download was successful.</returns>
        public async Task <bool> DownloadAsync()
        {
            if (IsDownloaded)
            {
                return(IsDownloaded);
            }
            if (Video == null)
            {
                return(false);
            }

            var fileName = ToSafeFileName(Video.Id);
            var path     = $"{APP_DIRECTORY}downloads\\{fileName}";

            var mediaStreamInfos = await youtubeClient.GetVideoMediaStreamInfosAsync(Video.Id);

            var streamInfo = mediaStreamInfos.Audio.Where(x => x.Container != Container.WebM).First();
            var extension  = streamInfo.Container.GetFileExtension();

            if (File.Exists($"{path}.{extension}"))
            {
                FilePath     = $"{path}.{extension}";
                IsDownloaded = true;
                return(true);
            }

            ConsoleHelper.WriteLine($"Now Downloading: \"{Video.Title}\"");
            await youtubeClient.DownloadMediaStreamAsync(streamInfo, $"{path}.{extension}").ContinueWith(task => { OnDownloadCompletion(); });

            FilePath = $"{path}.{extension}";
            return(true);
        }
Exemplo n.º 12
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);
            }
        }
        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);
        }
Exemplo n.º 14
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()
        }
Exemplo n.º 15
0
        public async void DownloadYoutube(string videoId, string videoName)
        {
            try
            {
                string youtubeUrl = "http://youtube.com/watch?v=" + videoId;
                string fixedName  = videoName.Replace("/", " ");
                string writePath  = Application.StartupPath + @"\Data\" + fixedName + ".mp4";

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

                var streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality();

                var ext = streamInfo.Container.GetFileExtension();
                await client.DownloadMediaStreamAsync(streamInfo, writePath);

                addUser(fixedName);
            }

            catch
            {
                MessageBox.Show("목록 추가가 불가능합니다.", "알림");
                return;
            }
        }
Exemplo n.º 16
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, "", "", "");
            }
        }
Exemplo n.º 17
0
        public static async void download()
        {
            var client = new YoutubeClient();

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

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

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

            // ...or highest quality & highest framerate MP4 video stream
            // var streamInfo = streamInfoSet.Video
            //    .Where(s => s.Container == Container.Mp4)
            //    .OrderByDescending(s => s.VideoQuality)
            //    .ThenByDescending(s => s.Framerate)
            //    .First();

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

            // Download stream to file -> in debug folder
            await client.DownloadMediaStreamAsync(streamInfo, $"downloaded_video.{ext}");
        }
Exemplo n.º 18
0
        async void DownloadVid(String url, String dir)


        {
            Action <double>   a = new Action <double>(updateProgressBar);
            Progress <double> p = new Progress <double>(a);

            try
            {
                var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(currentId);

                var streamInfo = streamInfoSet.Audio.WithHighestBitrate();

                // Get file extension based on stream's container
                var ext = "wav";


                // Download stream to file
                string[] array    = { dir, $"test.{ext}" };
                string   fullPath = System.IO.Path.Combine(array);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                await client.DownloadMediaStreamAsync(streamInfo, fullPath, p);
            }
            catch (Exception e)
            {
                if (e is FormatException)
                {
                    messageTxt.Text = "error parsing link";
                }
            }
        }
Exemplo n.º 19
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;
        }
Exemplo n.º 20
0
        public async Task Download()
        {
            var client = new YoutubeClient();

            var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(_id);

            var streamInfo = streamInfoSet.Audio.WithHighestBitrate();
            var ext        = streamInfo.Container.GetFileExtension();


            var artists = string.Join(",", _artists);

            var filename = $"{_title} - {artists}";


            var inputFile  = $@"{Settings.Default.DownloadPath}\{filename}.{ext}";
            var outputFile = $@"{Settings.Default.ConvertedPath}\{filename}.mp3";


            await client.DownloadMediaStreamAsync(streamInfo, $@"{Settings.Default.DownloadPath}\{filename}.{ext}", _progress);

            Debug.WriteLine("Download complete!");
            Debug.WriteLine("Now converting the file");


            await Task.Run(async() => await FileConverter.ConvertToMp3(inputFile, outputFile));

            await Task.Run(() => TagMp3.Tag(outputFile, _track));
        }
Exemplo n.º 21
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;
        }
Exemplo n.º 22
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.º 23
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();
        }
Exemplo n.º 24
0
        public static async Task <string> DownloadAndConvertVideoStreamAsync(string id, Stream output)
        {
            var video = await YoutubeClient.GetVideoAsync(id);

            Console.WriteLine($"Working on video [{id}]...");
            var set = await YoutubeClient.GetVideoMediaStreamInfosAsync(id);

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

            Directory.CreateDirectory(OutputDirectoryPath);
            var streamFileExt  = streamInfo.Container.GetFileExtension();
            var filename       = $"{cleanTitle}.{streamFileExt}";
            var streamFilePath = Path.Combine(OutputDirectoryPath, filename);
            await YoutubeClient.DownloadMediaStreamAsync(streamInfo, output);

            return(filename);
        }
Exemplo n.º 25
0
        private static async Task <string> DownloadAndConvertVideoAsync(Song song)
        {
            string id = song.Id;

            Console.WriteLine($"Working on video [{id}]...");


            try
            {
                YoutubeClient youtubeclient = new YoutubeClient();

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

                var set = await youtubeclient.GetVideoMediaStreamInfosAsync(id);

                string cleantitle;
                try
                {
                    cleantitle = Regex.Replace(video.Title, @"[^\w\.@-]", "",
                                               RegexOptions.None, TimeSpan.FromSeconds(1.5));
                }
                // If we timeout when replacing invalid characters,
                // we should return Empty.
                catch (RegexMatchTimeoutException)
                {
                    cleantitle = String.Empty;
                }
                Console.WriteLine($"{video.Title}");

                // Get highest bitrate audio-only or highest quality mixed stream
                var streamInfo = GetBestAudioStreamInfo(set);

                // Download
                Console.WriteLine("Downloading...");
                var streamFileExt  = streamInfo.Container.GetFileExtension();
                var streamFilePath = $"discordbot\\video.{streamFileExt}";
                File.Delete(streamFilePath);
                await youtubeclient.DownloadMediaStreamAsync(streamInfo, streamFilePath);

                // Convert to mp3
                //Console.WriteLine("Converting...");
                //var outputFilePath = $"{cleantitle}.mp3";
                //File.Delete(outputFilePath);
                //await FfmpegCli.SetArguments($"-i \"{streamFilePath}\" -q:a 0 -map a \"{outputFilePath}\" -y").ExecuteAsync();


                Console.WriteLine($"Downloaded video [{id}] to [{streamFilePath}]");

                return(streamFilePath);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return(null);
        }
Exemplo n.º 26
0
        private async void getVideo(string address, string saveLocation, bool video)
        {
            var client        = new YoutubeClient();
            var id            = YoutubeClient.ParseVideoId(address);
            var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(id);

            var streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality();
            var ext        = streamInfo.Container.GetFileExtension();

            if (video)
            {
                await client.DownloadMediaStreamAsync(streamInfo, saveLocation + "." + ext);
            }
            if (!video)
            {
                await client.DownloadMediaStreamAsync(streamInfo, saveLocation + "." + "mp3");

                // var idMatch =
            }
        }
        public async Task <VideoFileViewModel> DownloadVideo(string videoId)
        {
            var client        = new YoutubeClient();
            var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(videoId);

            var streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality();
            var ext        = streamInfo.Container.GetFileExtension();
            await client.DownloadMediaStreamAsync(streamInfo, "downloaded_video_" + videoId + "." + ext);

            return(new VideoFileViewModel());
        }
Exemplo n.º 28
0
        private async Task DownloadVideoAsync(Video video, string path)
        {
            string ValidName     = video.Title.ValidNameForWindows();
            var    streamInfoSet = await client.GetVideoMediaStreamInfosAsync(video.Id);

            var streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality();
            var ext        = streamInfo.Container.GetFileExtension();

            path.EnsureExsit();
            await client.DownloadMediaStreamAsync(streamInfo, $"{path}\\{ValidName}.{ext}", Progress);
        }
Exemplo n.º 29
0
        public async Task <ActionResult> CreateDownloadUrl(YoutubeReqeust request)
        {
            var _youtubeClient = new YoutubeClient();
            var _videoInfo     = await _youtubeClient.GetVideoAsync(request.VideoID);

            var _streamInfo = _videoInfo.MuxedStreamInfos.OrderByDescending(x => x.VideoQuality).FirstOrDefault();

            var _size   = _streamInfo.Size;
            var _sizeMb = (_size / 1024 / 1024);

            if (_sizeMb > 10)
            {
                throw new ArgumentOutOfRangeException("下載檔案超過 10MB");
            }

            if (_streamInfo == null)
            {
                throw new ArgumentNullException(nameof(_streamInfo));
            }

            var _fileExtension = _streamInfo.Container.GetFileExtension();

            //下載的影片檔案名稱與儲存路徑
            var _videoFileName = $"{_videoInfo.Id}.{_fileExtension}";
            var _videoFullPath = this.GetPath(_videoFileName);

            //轉換後的 MP3 檔案名稱與儲存路徑
            var _mp3FileName = $"{_videoInfo.Id}.mp3";
            var _mp3FullPath = this.GetPath(_mp3FileName);

            //下載 Youtube 影片
            await _youtubeClient.DownloadMediaStreamAsync(_streamInfo, _videoFullPath);

            //進行 MP3 格式檔案轉換
            var _inputMediaFile = new MediaFile()
            {
                Filename = _videoFullPath
            };
            var _outMediaFile = new MediaFile()
            {
                Filename = _mp3FullPath
            };

            using (var _engine = new Engine())
            {
                _engine.GetMetadata(_inputMediaFile);
                _engine.Convert(_inputMediaFile, _outMediaFile);
            }

            //影片轉換成 MP3 完成後刪除影片檔
            System.IO.File.Delete(_videoFullPath);

            return(Json(_videoInfo.Id));
        }
Exemplo n.º 30
0
        private static async Task DownloadVideoAsync(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}");

            // Get best streams
            var streamInfoSet = await YoutubeClient.GetVideoMediaStreamInfosAsync(id);

            var videoStreamInfo = streamInfoSet.Video.WithHighestVideoQuality();
            var audioStreamInfo = streamInfoSet.Audio.WithHighestBitrate();

            // Download streams
            Console.WriteLine("Downloading...");
            Directory.CreateDirectory(TempDirectoryPath);
            var videoStreamFileExt  = videoStreamInfo.Container.GetFileExtension();
            var videoStreamFilePath = Path.Combine(TempDirectoryPath, $"VID-{Guid.NewGuid()}.{videoStreamFileExt}");
            await YoutubeClient.DownloadMediaStreamAsync(videoStreamInfo, videoStreamFilePath);

            var audioStreamFileExt  = audioStreamInfo.Container.GetFileExtension();
            var audioStreamFilePath = Path.Combine(TempDirectoryPath, $"AUD-{Guid.NewGuid()}.{audioStreamFileExt}");
            await YoutubeClient.DownloadMediaStreamAsync(audioStreamInfo, audioStreamFilePath);

            // Mux streams
            Console.WriteLine("Combining...");
            Directory.CreateDirectory(OutputDirectoryPath);
            var outputFilePath = Path.Combine(OutputDirectoryPath, $"{cleanTitle}.mp4");
            await FfmpegCli.ExecuteAsync($"-i \"{videoStreamFilePath}\" -i \"{audioStreamFilePath}\" -shortest \"{outputFilePath}\" -y");

            // Delete temp files
            Console.WriteLine("Deleting temp files...");
            File.Delete(videoStreamFilePath);
            File.Delete(audioStreamFilePath);

            Console.WriteLine($"Downloaded video [{id}] to [{outputFilePath}]");
        }