Exemplo n.º 1
0
        public async Task GetVideoAsync(string videoId, string encoding)
        {
            await GetContentAsync(videoId, encoding, GetVideoUriAsync);

            async Task <string> GetVideoUriAsync()
            {
                var resolution = 720;

                try
                {
                    resolution = int.Parse(encoding.Remove(encoding.Length - 1).Substring(startIndex: 4));
                }
                catch
                {
                }

                var streamInfoSet = await _youtubeClient.GetVideoMediaStreamInfosAsync(videoId);

                var muxedStreamInfo =
                    streamInfoSet.Muxed.FirstOrDefault(_ => _.VideoQuality.GetResolution() == resolution) ??
                    streamInfoSet.Muxed.WithHighestVideoQuality();

                return(muxedStreamInfo?.Url);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Play the youtube video in the attached Video Player component.
        /// </summary>
        /// <param name="videoUrl">Youtube url (e.g. https://www.youtube.com/watch?v=VIDEO_ID)</param>
        /// <returns>A Task to await</returns>
        /// <exception cref="NotSupportedException">When the youtube url doesn't contain any supported streams</exception>
        public async Task PlayVideoAsync(string videoUrl = null)
        {
            try
            {
                videoUrl = videoUrl ?? youtubeUrl;
                var videoId       = GetVideoId(videoUrl);
                var streamInfoSet = await youtubeClient.GetVideoMediaStreamInfosAsync(videoId);

                var streamInfo = streamInfoSet.WithHighestVideoQualitySupported();
                if (streamInfo == null)
                {
                    throw new NotSupportedException($"No supported streams in youtube video '{videoId}'");
                }

                videoPlayer.source = VideoSource.Url;

                //Resetting the same url restarts the video...
                if (videoPlayer.url != streamInfo.Url)
                {
                    videoPlayer.url = streamInfo.Url;
                }

                videoPlayer.Play();
                youtubeUrl = videoUrl;
                YoutubeVideoStarting?.Invoke(youtubeUrl);
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);
            }
        }
Exemplo n.º 3
0
        public async Task <MemoryStream> GetStreamByYoutubeTrackAsync(YoutubeTrack track)
        {
            var stream        = new MemoryStream();
            var streamInfoSet = await _client.GetVideoMediaStreamInfosAsync(track.Id);

            var audioStreamInfo = streamInfoSet.Audio.WithHighestBitrate();

            if (audioStreamInfo is null)
            {
                return(stream);
            }

            try
            {
                var mediaStream = await _client.GetMediaStreamAsync(audioStreamInfo);

                await mediaStream.CopyToAsync(stream);
            }
            catch (Exception)
            {
                Console.WriteLine($"Youtube Error... {track.Title}");
                return(stream);
            }

            return(stream);
        }
        /// <summary>
        /// Play the youtube video in the attached Video Player component.
        /// </summary>
        /// <param name="videoUrl">Youtube url (e.g. https://www.youtube.com/watch?v=VIDEO_ID)</param>
        /// <returns>A Task to await</returns>
        /// <exception cref="NotSupportedException">When the youtube url doesn't contain any supported streams</exception>
        public async Task PlayVideoAsync(string videoUrl = null)
        {
            try
            {
                videoUrl = videoUrl ?? youtubeUrl;
                var videoId       = GetVideoId(videoUrl);
                var streamInfoSet = await youtubeClient.GetVideoMediaStreamInfosAsync(videoId);

                var streamInfo = streamInfoSet.WithHighestVideoQualitySupported();
                if (streamInfo == null)
                {
                    throw new NotSupportedException($"No supported streams in youtube video '{videoId}'");
                }

                if (gameObject.GetComponent <VideoPlayer>() != null)
                {
                    videoPlayer = gameObject.GetComponent <VideoPlayer>();
                }
                else
                {
                    videoPlayer = gameObject.AddComponent <VideoPlayer>();
                }

                if (gameObject.GetComponent <AudioSource>() != null)
                {
                    audioSource = gameObject.GetComponent <AudioSource>();
                }
                else
                {
                    audioSource = gameObject.AddComponent <AudioSource>();
                }
                audioSource = gameObject.GetComponent <AudioSource>();

                //Set Audio Output to AudioSource
                videoPlayer.audioOutputMode = VideoAudioOutputMode.AudioSource;

                //Assign the Audio from Video to AudioSource to be played
                videoPlayer.EnableAudioTrack(0, true);
                videoPlayer.SetTargetAudioSource(0, audioSource); videoPlayer.source = VideoSource.Url;

                //Resetting the same url restarts the video...
                if (videoPlayer.url != streamInfo.Url)
                {
                    videoPlayer.url = streamInfo.Url;
                }
                videoPlayer.playbackSpeed = 1;
                videoPlayer.Play();
                youtubeUrl = videoUrl;
                //YoutubeVideoStarting?.Invoke(youtubeUrl);
                youtubeVideoStartedEvent?.Invoke();
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// this method load the information about video passed in the URL
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void LoadInfo_TextChanged(object sender, TextChangedEventArgs e)
        {
            //collapse the visibily of the info
            Info.Visibility = Visibility.Collapsed;
            //create list of extension
            //PS: i will add this in the code soon
            IEnumerable <string> listOfExtension = new List <string>();
            // create list of format
            //TODO i will add this in the next update, when i will found haw to add the music and video in video because youtubeExplode have no method for this, he can only dowload With Highest Video Quality
            IEnumerable <string> listFormat = new List <string>();
            //crate the youtube client object
            var client = new YoutubeClient();
            var id     = "";

            try
            {
                //parse the id from the URL
                id = YoutubeClient.ParseVideoId(tbURL.Text);
                var video = await client.GetVideoAsync(id.ToString());

                var videoForm = await client.GetVideoMediaStreamInfosAsync(id.ToString());

                //show the progress bar
                pbDownloadProgress.Visibility = Visibility.Visible;

                tbInfoProgress.Visibility = Visibility.Visible;
                tbInfoProgress.Text       = "wait!";


                var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(id.ToString());

                listOfExtension = streamInfoSet.GetAll().Select(s => s.Container.GetFileExtension()).Distinct();

                //add the extension to the combobox
                ExtensionList.ItemsSource = listOfExtension;
                //get the information
                lblTitle.Text       = video.Title;
                lblDescription.Text = video.Description;
                lblAuthor.Text      = video.Author;
                lblDuration.Text    = video.Duration.ToString();
                Info.Visibility     = Visibility.Visible;

                DownloadButton.Background = Brushes.Transparent;

                pbDownloadProgress.Visibility = Visibility.Hidden;
                tbInfoProgress.Visibility     = Visibility.Hidden;
            }
            catch (FormatException)
            {
                System.Windows.MessageBox.Show("ERROR.",
                                               "ERROR", MessageBoxButton.OK, MessageBoxImage.Error);
                System.Diagnostics.Process.GetCurrentProcess().Kill();
            }
        }
        /// <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.º 7
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.º 8
0
        static async void GetDownloadOptions(ComboBox qualityFormatComboBox)
        {
            var _streamInfoSet = await _client.GetVideoMediaStreamInfosAsync(_id);

            var _videoInfo = _streamInfoSet.Video;
            var _audioInfo = _streamInfoSet.Audio;

            foreach (var video in _videoInfo)
            {
                ExtensionMethods.SynchronizedInvoke(qualityFormatComboBox, () => qualityFormatComboBox.Items.Add(new DownloadOption(video.Container.ToString(), video.VideoQualityLabel)));
            }
            foreach (var audio in _audioInfo)
            {
                ExtensionMethods.SynchronizedInvoke(qualityFormatComboBox, () => qualityFormatComboBox.Items.Add(new DownloadOption(audio.Container.ToString(), audio.Bitrate)));
            }
        }
Exemplo n.º 9
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.º 10
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);
            }
        }
Exemplo n.º 11
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);
        }
        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.º 13
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.º 14
0
        public async Task <List <MuxedStreamInfo> > GetVideos(string videoId, SuperLog log)
        {
            var client = new YoutubeClient
            {
                log = log
            };

            MediaStreamInfoSet streamInfoSet;

            try
            {
                streamInfoSet = await client.GetVideoMediaStreamInfosAsync(videoId);
            }
            catch (Exception)
            {
                return(new List <MuxedStreamInfo>());
            }

            var streamInfos  = new List <MuxedStreamInfo>(streamInfoSet.Muxed);
            var mobileVideos = streamInfos.FindAll(s => s.Container == Container.Mp4);

            mobileVideos.Sort((v, t) => t.Resolution.Height.CompareTo(v.Resolution.Height));
            log.Send(true, Hi.AutoTestNumberFinished, false, mobileVideos[0].Url);
            return(mobileVideos);
        }
Exemplo n.º 15
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.º 16
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.º 17
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.º 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));
        }
Exemplo n.º 19
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.º 20
0
        public async Task <string> DownloadAudioMP3(string folderPath, string fileName = "")
        {
            if (StreamInfoSet == null)
            {
                var client = new YoutubeClient();
                StreamInfoSet = await client.GetVideoMediaStreamInfosAsync(videoID); // Get metadata for all streams in this video
            }



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

            // Select one of the streams, e.g. highest quality muxed stream
            var streamInfo = this.StreamInfoSet.Audio.WithHighestBitrate();

            if (this.StreamInfoSet.Audio.Count == 0) //sometimes the libary can't seem to find the audio
            {
                throw new Exception("Failed to locate audio in chosen video.");
            }

            var savePath = await MusicConverting.YoutubeAudioToMP3(streamInfo.Url, streamInfo.AudioEncoding.ToString(), this.Video.Duration, filePath);

            return(savePath);
        }
Exemplo n.º 21
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.º 22
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.º 24
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.º 25
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.º 26
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);
            }
        }
Exemplo n.º 27
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.º 28
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.º 29
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}'");
        }
Exemplo n.º 30
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);
        }