/// <inheritdoc />
        public async Task DownloadVideoAsync(MediaStreamInfoSet mediaStreamInfoSet, string filePath, string format,
                                             IProgress <double> progress         = null,
                                             CancellationToken cancellationToken = default(CancellationToken))
        {
            mediaStreamInfoSet.GuardNotNull(nameof(mediaStreamInfoSet));
            filePath.GuardNotNull(nameof(filePath));
            format.GuardNotNull(nameof(format));

            var mediaStreamInfos = new List <MediaStreamInfo>();

            // Get best audio stream (priority: transcoding -> bitrate)
            var audioStreamInfo = mediaStreamInfoSet.Audio
                                  .OrderByDescending(s => !IsTranscodingRequired(s.Container, format))
                                  .ThenByDescending(s => s.Bitrate)
                                  .FirstOrDefault();

            // Add to result
            mediaStreamInfos.Add(audioStreamInfo);

            // If needs video - get best video stream (priority: quality -> framerate -> transcoding)
            if (!IsAudioOnlyFormat(format))
            {
                var videoStreamInfo = mediaStreamInfoSet.Video
                                      .OrderByDescending(s => s.VideoQuality)
                                      .ThenByDescending(s => s.Framerate)
                                      .ThenByDescending(s => !IsTranscodingRequired(s.Container, format))
                                      .FirstOrDefault();

                // Add to result
                mediaStreamInfos.Add(videoStreamInfo);
            }

            // Download media streams and process them
            await DownloadAndProcessMediaStreamsAsync(mediaStreamInfos, filePath, format, progress, cancellationToken);
        }
Ejemplo n.º 2
0
        /// <summary>
        ///  Downloads audio and saves it to the provided audioPath folder
        /// </summary>
        /// <param name="id">id of the youtube video</param>
        /// <param name="audioPath">Path where file should be saved without extension at the end</param>
        /// <returns></returns>
        public async Task DownloadAudioAsync(string id, string audioPath)
        {
            MediaStreamInfoSet streamInfoSet = await client.GetVideoMediaStreamInfosAsync(id);

            var audioInfo = streamInfoSet.Audio.WithHighestBitrate();
            await client.DownloadMediaStreamAsync(audioInfo, audioPath);
        }
Ejemplo n.º 3
0
 private static MediaStreamInfo GetBestVideoStreamInfo(MediaStreamInfoSet set)
 {
     if (set.Muxed.Any())
     {
         return(set.Muxed.WithHighestVideoQuality());
     }
     throw new Exception("No applicable media streams found for this video");
 }
Ejemplo n.º 4
0
 /// <summary>
 /// Gets the muxed stream with highest video quality and Mp4 container.
 /// Returns null if sequence is empty.
 /// </summary>
 public static MuxedStreamInfo WithHighestVideoQualitySupported(this MediaStreamInfoSet streamInfoSet)
 {
     if (streamInfoSet == null)
     {
         throw new ArgumentNullException(nameof(streamInfoSet));
     }
     return(streamInfoSet.Muxed.WithHighestVideoQualitySupported());
 }
Ejemplo n.º 5
0
 private static MediaStreamInfo GetBestAudioStreamInfo(MediaStreamInfoSet set)
 {
     if (set.Audio.Any(a => a.AudioEncoding == AudioEncoding.Aac))
     {
         return(set.Audio.First(a => a.AudioEncoding == AudioEncoding.Aac));
     }
     throw new Exception("No applicable media streams found for this video");
 }
        /// <inheritdoc />
        public async Task DownloadVideoAsync(MediaStreamInfoSet mediaStreamInfoSet, string filePath, string format,
                                             IProgress <double>?progress = null, CancellationToken cancellationToken = default)
        {
            // Select best media stream infos based on output format
            var mediaStreamInfos = GetBestMediaStreamInfos(mediaStreamInfoSet, format).ToArray();

            // Download media streams and process them
            await DownloadAndProcessMediaStreamsAsync(mediaStreamInfos, filePath, format, progress, cancellationToken);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Downloads video and saves it to the provided videoPath folder
        /// </summary>
        /// <param name="id">ID of the video to download</param>
        /// <param name="quality">Choosen quality of the video</param>
        /// <param name="videoPath">Path where file should be saved and what file should be named with extension at the end (.mp4/.mp3).</param>
        /// <returns></returns>
        public async Task DownloadVideoAsync(string id, string quality, string videoPath)
        {
            MediaStreamInfoSet streamInfoSet = await client.GetVideoMediaStreamInfosAsync(id);

            var audioStreamInfo  = streamInfoSet.Audio.WithHighestBitrate();
            var videoStreamInfo  = streamInfoSet.Video.FirstOrDefault(c => c.VideoQualityLabel == quality);
            var mediaStreamInfos = new MediaStreamInfo[] { audioStreamInfo, videoStreamInfo };
            await converter.DownloadAndProcessMediaStreamsAsync(mediaStreamInfos, videoPath, "mp4");
        }
Ejemplo n.º 8
0
        private async void button2_Click(object sender, EventArgs e)
        {
            button2.Enabled = false;
            Cursor          = Cursors.WaitCursor;

            button1.Enabled = false;
            var url = textBox1.Text;
            var id  = "";

            if (url.Contains("youtube.com") || url.Contains("youtu.be"))
            {
                id = YoutubeClient.ParseVideoId(url); // "bnsUkE8i0tU"
            }
            else
            {
                id = url;
            }

            var   client = new YoutubeClient();
            Video video;

            try
            {
                video = await client.GetVideoAsync(id);
            }
            catch (Exception)
            {
                MessageBox.Show("Video bulunamadı.");
                button2.Enabled = true;
                Cursor          = Cursors.Default;
                return;
            }



            streamInfoSet = await client.GetVideoMediaStreamInfosAsync(id);

            comboBox1.Items.Clear();
            foreach (var v in streamInfoSet.Muxed)
            {
                comboBox1.Items.Add($"Video: {v.VideoQualityLabel} {v.Size} {v.VideoEncoding} {v.Container.GetFileExtension()}");
            }
            //foreach (var a in streamInfoSet.Audio)
            //{
            //    comboBox1.Items.Add($"Audio: {a.AudioEncoding} {a.Size}");
            //}
            if (comboBox1.Items.Count > 0)
            {
                comboBox1.SelectedIndex = 0;
            }
            button2.Enabled = true;
            button1.Enabled = true;
            Cursor          = Cursors.Default;
        }
Ejemplo n.º 9
0
        private async Task <String> RetrieveMusicInfo()
        {
            if (string.IsNullOrEmpty(Music.SourceUrl))
            {
                MediaStreamInfoSet infoSet = await _youtubeClient.GetVideoMediaStreamInfosAsync(Music.Id);

                AudioStreamInfo info = infoSet.Audio.WithHighestBitrate();
                return(info?.Url);
            }
            return(Music.SourceUrl);
        }
Ejemplo n.º 10
0
 public static MediaStreamInfo GetBestAudioStreamInfo(this MediaStreamInfoSet set)
 {
     if (set.Audio.Any())
     {
         return(set.Audio.WithHighestBitrate());
     }
     if (set.Muxed.Any())
     {
         return(set.Muxed.WithHighestVideoQuality());
     }
     throw new Exception("No applicable media streams found for this video");
 }
Ejemplo n.º 11
0
        public static async Task <string> New_Pull(string vidId)
        {
            YoutubeClient      client    = new YoutubeClient();
            MediaStreamInfoSet videoInfo = await client.GetVideoMediaStreamInfosAsync(vidId);


            string RS = null;

            try { RS = videoInfo.Audio.OrderBy(p => p.Bitrate).First().Url; } catch (Exception ex) { }

            return(RS);
        }
Ejemplo n.º 12
0
        public async Task <VideoDetails> GetVideoMetadataAsync(string videoID)
        {
            var video = await client.GetVideoAsync(videoID);

            MediaStreamInfoSet streamInfoSet = await client.GetVideoMediaStreamInfosAsync(videoID);

            IEnumerable <string> qualities = SortQualities(streamInfoSet.GetAllVideoQualityLabels());

            return(new VideoDetails()
            {
                id = videoID, ChannelName = video.Author, Title = video.Title, qualities = qualities, thumbnails = video.Thumbnails
            });
        }
        private async Task DownloadMusicFile(HttpClient httpclient, DataRepository _repository, YoutubeClient _ytclient, YouTubeSourceMedia media)
        {
            _logger.LogInformation($"Getting metadata for {media.YouTubeId}");

            try
            {
                var mediainfo = await _ytclient.GetVideoAsync(media.YouTubeId);

                var channel = await _ytclient.GetVideoAuthorChannelAsync(media.YouTubeId);

                MediaStreamInfoSet info = null;

                info = await _ytclient.GetVideoMediaStreamInfosAsync(media.YouTubeId);

                var audioinfo = info.Audio
                                .OrderBy(x => x.Size)
                                .Where(x => x.AudioEncoding == AudioEncoding.Aac)
                                .FirstOrDefault();

                media.FilePath = Path.Combine(media.GetType().Name, channel.Id, $"{media.YouTubeId}.m4a")
                                 .GetSafePath();
                media.ArtworkPath = Path.Combine(media.GetType().Name, channel.Id, $"{media.YouTubeId}.jpg")
                                    .GetSafePath();

                var downloadfilepath    = Path.Combine(_config.SourcesPath, media.FilePath).GetSafePath();
                var downloadartworkpath = Path.Combine(_config.SourcesPath, media.ArtworkPath).GetSafePath();

                _logger.LogInformation($"Downloading file {downloadfilepath}");
                Directory.CreateDirectory(Path.GetDirectoryName(downloadfilepath));
                await _ytclient.DownloadMediaStreamAsync(audioinfo, downloadfilepath);

                await File.WriteAllBytesAsync(downloadartworkpath, await GetThumbnail(httpclient, mediainfo));

                media.IsDownloaded = true;
                await _repository.UpdateMedia(media);
            }
            catch (YoutubeExplode.Exceptions.VideoUnplayableException ex)
            {
                _logger.LogError(ex, $"Unable to download {media.YouTubeId}");
                media.IsActive = false;
                await _repository.UpdateMedia(media);

                return;
            }

            _logger.LogInformation($"Download for {media.YouTubeId} completed");
        }
Ejemplo n.º 14
0
        public override bool Download(int SelectedIndex)
        {
            if (SelectedIndex == -1)
            {
                SelectedIndex = 0;
            }

            if (FileCacheDictionary.ContainsId(Id))
            {
                Console.WriteLine("Already Exists!");
                return(false);
            }
            else
            {
                WebClient client = new WebClient();
                client.DownloadProgressChanged += Client_DownloadProgressChanged;
                client.DownloadFileCompleted   += Client_DownloadFileCompleted;

                YoutubeClient      youtubeClient = new YoutubeClient();
                MediaStreamInfoSet streamInfoSet = youtubeClient.GetVideoMediaStreamInfosAsync(Id).Result;
                MuxedStreamInfo    streamInfo    = streamInfoSet.Muxed.WithHighestVideoQuality();

                if (streamInfo == null)
                {
                    throw new Exception("다운로드 할 수 없는 영상입니다.");
                }

                Console.WriteLine($"Audio:{streamInfo.AudioEncoding.ToString()} Quality : {streamInfo.VideoQualityLabel} Download URL : {streamInfo.Url}");

                string basePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Delight\\External Sources Cache\\";

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


                string path = basePath + Path.GetRandomFileName() + ".mp4";

                client.DownloadFileAsync(new Uri(streamInfo.Url), path);
                FileCacheDictionary.AddPair(Title, path, Id);

                Console.WriteLine(path);
                return(true);
            }
        }
        private async Task <bool> GetVideoData()
        {
            var    client = new YoutubeClient();
            string id     = Source;

            //Convert it to a regular ID if it is a youtube link
            try { id = YoutubeClient.ParseVideoId(Source); }
            catch { }

            //Get the video
            try { videoStreams = await client.GetVideoMediaStreamInfosAsync(id); }
            catch { return(false); }

            //Store the video urls and info
            Constants.videoInfo = videoStreams;

            return(true);
        }
        /// <summary>
        /// Selects Opus audio if available, otherwise Vorbis or AAC.
        /// </summary>
        /// <param name="list">The list of available audios.</param>
        /// <returns>The audio to download.</returns>
        public static AudioStreamInfo SelectBestAudio(MediaStreamInfoSet vinfo, DownloadOptions options)
        {
            if (vinfo == null || vinfo.Audio.Count() == 0)
            {
                return(null);
            }

            var BestAudio = (from v in vinfo.Audio
                             // Opus encodes ~20% better, Vorbis ~10% better than AAC
                             let Preference = (int)(v.Size * (v.AudioEncoding == AudioEncoding.Opus ?  1.2 : v.AudioEncoding == AudioEncoding.Vorbis ? 1.1 : 1))
                                              where options.PreferredAudio == SelectStreamFormat.Best ||
                                              (options.PreferredAudio == SelectStreamFormat.MP4 && (v.AudioEncoding == AudioEncoding.Aac || v.AudioEncoding == AudioEncoding.Mp3)) ||
                                              (options.PreferredAudio == SelectStreamFormat.VP9 && (v.AudioEncoding == AudioEncoding.Opus || v.AudioEncoding == AudioEncoding.Vorbis))
                                              orderby Preference descending
                                              select v).FirstOrDefault();

            return(BestAudio);
        }
Ejemplo n.º 17
0
        public async Task <string> DownloadAudio(string id)
        {
            MediaStreamInfoSet audioStreamInfoSet = await m_youtubeClient.GetVideoMediaStreamInfosAsync(id);

            string filename = null;

            foreach (AudioStreamInfo audioStreamInfo in audioStreamInfoSet.Audio)
            {
                if (audioStreamInfo.AudioEncoding != AudioEncoding.Opus && audioStreamInfo.AudioEncoding != AudioEncoding.Vorbis)
                {
                    string extension = audioStreamInfo.Container.GetFileExtension();
                    filename = string.Format("{0}.{1}", id, extension);

                    await m_youtubeClient.DownloadMediaStreamAsync(audioStreamInfo, "Library\\" + filename);
                }
            }

            return(filename);
        }
        public static bool DownloadVideoViaYoutubeExplode(string url, string successPath, string failurePath, Action <double> progressHandler = null)
        {
            try
            {
                string             id            = YoutubeClient.ParseVideoId(url);
                YoutubeClient      client        = new YoutubeClient();
                MediaStreamInfoSet streamInfoSet = client.GetVideoMediaStreamInfosAsync(id).Result;

                MuxedStreamInfo streamInfo = streamInfoSet.Muxed.First(m => m.Container.GetFileExtension().ToLower() == "mp4");
                //string ext = streamInfo.Container.GetFileExtension();
                client.DownloadMediaStreamAsync(streamInfo, successPath, progressHandler == null ? null :  new Progress <double>(progressHandler)).Wait();
                return(true);
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception);
                File.Create(failurePath).Close();
                return(false);
            }
        }
Ejemplo n.º 19
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            string link = linkBox.Text;
            var    id   = YoutubeClient.ParseVideoId(link);

            client = new YoutubeClient();
            video  = await client.GetVideoAsync(id);

            streamInfoSet = await client.GetVideoMediaStreamInfosAsync(video.Id);

            streamInfo = streamInfoSet.Audio.WithHighestBitrate();


            ext = streamInfo.Container.GetFileExtension();

            MediaStreamInfo m =

                audioStreamInfo = streamInfoSet.Audio
                                  .OrderByDescending(s => s.Container == Container.WebM)
                                  .ThenByDescending(s => s.Bitrate)
                                  .First();

            var pic = new BitmapImage(new Uri(video.Thumbnails.HighResUrl));

            thumbnail.Source = pic;

            //pic.CreateOptions = BitmapCreateOptions.None;
            //WriteableBitmap wb = new WriteableBitmap(pic);
            //ImageConverter converter = new ImageConverter();
            //byte[] b = (byte[])converter.ConvertTo(m, typeof(byte[]));

            //MemoryStream ms = new MemoryStream(b);


            var webClient = new WebClient();

            byte[] imageBytes = webClient.DownloadData(video.Thumbnails.HighResUrl);
            picture = new Picture(imageBytes);

            titleInfo.Text = video.Title;
        }
Ejemplo n.º 20
0
        public static async Task DownloadVideo(string videoID, string filePath)
        {
            var client = new YoutubeClient();
            MediaStreamInfoSet streamInfoSet = await client.GetVideoMediaStreamInfosAsync(videoID);

            var video = await client.GetVideoAsync(videoID);

            var streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality();

            var normalizedFileSize = NormalizeFileSize(streamInfo.Size);


            // Compose file name, based on metadata

            var fileExtension = streamInfo.Container.GetFileExtension();

            var fileName = $"{videoID}.{fileExtension}"; // ???

            //download youtube video,
            await client.DownloadMediaStreamAsync(streamInfo, filePath);
        }
Ejemplo n.º 21
0
        private List <MediaType> GetMediaTypeInfo(string mediaId)
        {
            List <MediaType> result = new List <MediaType>();

            try
            {
                if (!String.IsNullOrWhiteSpace(mediaId))
                {
                    MediaStreamInfoSet streamInfoSet = this.GetMediaStreamInfo(mediaId);

                    if (streamInfoSet.Audio != null)
                    {
                        AudioStreamInfo asiItem = streamInfoSet.Audio.FirstOrDefault(s => s.Container.GetFileExtension().ToLower().Equals("mp4"));
                        if (asiItem != null)
                        {
                            result.Add(new MediaType(MediaType.ExtensionType.MP3, null, asiItem.Size));
                        }
                    }
                    //Nie uzywamy Video, bo obsługuje tylko obraz, aby go połączyć z dźwiękiem potrzeba dodatkowo Youtube.Converter + FFMPEG
                    if (streamInfoSet.Muxed != null)
                    {
                        foreach (MuxedStreamInfo vsiItem in streamInfoSet.Muxed.Where(s => s.Container.GetFileExtension().ToLower().Equals("mp4")))
                        {
                            result.Add(new MediaType(MediaType.ExtensionType.MP4, vsiItem.VideoQualityLabel, vsiItem.Size));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                this.CancelOperation?.Dispose();
                this.CancelOperation = null;
            }
            return(result);
        }
        /// <summary>
        /// Returns the best format from the list in this order of availability: WebM, Mp4 or Flash.
        /// Mp4 will be chosen if WebM is over 35% smaller.
        /// </summary>
        /// <param name="list">The list of videos to chose from.</param>
        /// <returns>The best format available.</returns>
        public static BestFormatInfo SelectBestFormat(MediaStreamInfoSet vstream, DownloadOptions options)
        {
            var MaxResolutionList = (from v in vstream.Audio.Cast <MediaStreamInfo>().Union(vstream.Video).Union(vstream.Muxed)
                                     where (options.MaxQuality == 0 || GetVideoHeight(v) <= options.MaxQuality)
                                     orderby GetVideoHeight(v) descending
                                     orderby GetVideoFrameRate(v) descending
                                     select v).ToList();

            MaxResolutionList = MaxResolutionList.Where(v => GetVideoHeight(v) == GetVideoHeight(MaxResolutionList.First())).ToList();
            //double Framerate = GetVideoFrameRate(MaxResolutionList.FirstOrDefault());
            //if (Framerate > 0)
            //    MaxResolutionList = MaxResolutionList.Where(v => GetVideoFrameRate(v) == Framerate).ToList();

            MediaStreamInfo BestVideo = (from v in MaxResolutionList
                                         // WebM VP9 encodes ~30% better. non-DASH is VP8 and isn't better than MP4.
                                         let Preference = (int)((GetVideoEncoding(v) == VideoEncoding.Vp9) ? v.Size * 1.3 : v.Size)
                                                          where options.PreferredFormat == SelectStreamFormat.Best ||
                                                          (options.PreferredFormat == SelectStreamFormat.MP4 && GetVideoEncoding(v) == VideoEncoding.H264) ||
                                                          (options.PreferredFormat == SelectStreamFormat.VP9 && GetVideoEncoding(v) == VideoEncoding.Vp9)
                                                          orderby Preference descending
                                                          select v).FirstOrDefault();

            if (BestVideo == null)
            {
                BestVideo = MaxResolutionList.FirstOrDefault();
            }
            if (BestVideo != null)
            {
                BestFormatInfo Result = new BestFormatInfo {
                    BestVideo = BestVideo,
                    BestAudio = SelectBestAudio(vstream, options)
                };
                return(Result);
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 23
0
        public SongInQueue DownloadSong(string link)
        {
            string      guid         = Guid.NewGuid().ToString();
            SongInQueue result       = new SongInQueue();
            string      fullFilePath = _musicStorage + guid;

            YoutubeClient client = new YoutubeClient();

            try
            {
                _log.Debug($"Started processing { link }");
                string             parsedYoutubeId = YoutubeClient.ParseVideoId(link);
                MediaStreamInfoSet streamInfoSet   = client.GetVideoMediaStreamInfosAsync(parsedYoutubeId).Result;

                YoutubeExplode.Models.Video video = client.GetVideoAsync(parsedYoutubeId).Result;
                result.Name = video.Title;
                AudioStreamInfo streamInfo = streamInfoSet.Audio.FirstOrDefault();

                string ext = streamInfo.Container.GetFileExtension();
                fullFilePath += $".{ ext }";

                IProgress <double> progress = new YoutubeExtractorClientProgress($"{result.Name} - { guid }");


                client.DownloadMediaStreamAsync(streamInfo, fullFilePath, progress).Wait();
                var inputFile = new MediaFile(fullFilePath);

                result.FilePath = fullFilePath;

                _log.Debug("Finished processing file " + link);
                return(result);
            }
            catch (Exception ex)
            {
                _log.Error($"Error while downloading youtube song", ex);
                throw ex;
            }
        }
Ejemplo n.º 24
0
        static async void DownloadAudio(MediaStreamInfoSet mediaStreamInfoSet, string title, MaterialListView downloadQueueMaterialListView, string format, long bitrate, int _listViewItems, string savePath, MaterialCheckBox deleteDoneCheckBox)
        {
            var _audioStreamInfo = mediaStreamInfoSet.Audio.OrderByDescending(a => a.Bitrate / 1024 == bitrate).First();

            IProgress <double> progress = new Progress <double>(p =>
            {
                ExtensionMethods.SynchronizedInvoke(downloadQueueMaterialListView, () => downloadQueueMaterialListView.Items[_listViewItems].SubItems[4].Text = (p * 100).ToString("0.00") + "%");

                if (p * 100 == 100)
                {
                    ExtensionMethods.SynchronizedInvoke(downloadQueueMaterialListView, () => downloadQueueMaterialListView.Items[_listViewItems].SubItems[4].Text = "Done!");
                    DatabaseOperations.AddNewRecord(Settings.Default.Guid, title, format, savePath);

                    if (deleteDoneCheckBox.Checked == true)
                    {
                        Thread.Sleep(2000);
                        ExtensionMethods.SynchronizedInvoke(downloadQueueMaterialListView, () => downloadQueueMaterialListView.Items[_listViewItems].Remove());
                    }
                }
            });

            await Task.Run(() => _client.DownloadMediaStreamAsync(_audioStreamInfo, savePath + ".mp3", progress));
        }
Ejemplo n.º 25
0
        private MediaStreamInfoSet GetMediaStreamInfo(string mediaId)
        {
            Task <MediaStreamInfoSet> streamInfoSetLoader = null;

            try
            {
                this.CancelOperation = new CancellationTokenSource();
                streamInfoSetLoader  = this.youtubeClient.GetVideoMediaStreamInfosAsync(mediaId);
                streamInfoSetLoader.Wait(MediaStreamLoadTimeout, this.CancelOperation.Token);
                MediaStreamInfoSet result = streamInfoSetLoader.Result as MediaStreamInfoSet;
                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                this.CancelOperation?.Dispose();
                this.CancelOperation = null;
                streamInfoSetLoader?.Dispose();
            }
        }
Ejemplo n.º 26
0
        private static async Task <SongInfo> GetVideoInfo(EduardoContext context, string input)
        {
            List <Video> videos = await VideoHelper.GetOrSearchVideoAsync(input);

            if (videos == null || videos.Count == 0)
            {
                return(null);
            }

            Video chosenVideo = videos.FirstOrDefault();

            if (chosenVideo == null)
            {
                return(null);
            }

            MediaStreamInfoSet streamInfo = await VideoHelper.GetMediaStreamInfoAsync(chosenVideo);

            AudioStreamInfo stream = streamInfo.Audio.OrderByDescending(a => a.Bitrate).FirstOrDefault();

            if (stream == null)
            {
                return(null);
            }

            return(new SongInfo
            {
                Name = chosenVideo.Title,
                Duration = chosenVideo.Duration,
                VideoId = chosenVideo.Id,
                Url = chosenVideo.GetShortUrl(),
                StreamUrl = stream.Url,
                RequestedBy = context.User as IGuildUser,
                Description = chosenVideo.Description,
                ThumbnailUrl = chosenVideo.Thumbnails.StandardResUrl
            });
        }
Ejemplo n.º 27
0
        public async Task NEWLIBRARY_GetVideoAsync()
        {
            try
            {
                var id     = YoutubeClient.ParseVideoId(Url);
                var client = new YoutubeClient();
                var video  = await client.GetVideoAsync(id.ToString());

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

                streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality();

                DirectURL     = streamInfo.Url;
                Title         = video.Title;
                Duration      = video.Duration;
                Resolution    = new Size(streamInfo.Resolution.Width, streamInfo.Resolution.Height);
                ImageUrl      = YoutubeGet.GetImage(Url);
                PrevImagesUrl = YoutubeGet.GetPrevImages(Url);
            }
            catch
            {
                MessageBox.Show("Error creating YoutubeVideoInfo object. ");
            }
        }
Ejemplo n.º 28
0
        static async void DownloadVideo(MediaStreamInfoSet mediaStreamInfoSet, string title, MaterialListView downloadQueueMaterialListView, string format, string quality, int _listViewItems, string savePath, MaterialCheckBox deleteDoneCheckBox)
        {
            var _audioStreamInfo  = mediaStreamInfoSet.Audio.OrderByDescending(a => a.Bitrate).First();
            var _videoStreamInfo  = mediaStreamInfoSet.Video.Where(v => v.Container.ToString() == format && v.VideoQualityLabel == quality).First();
            var _mediaStreamInfos = new MediaStreamInfo[] { _audioStreamInfo, _videoStreamInfo };

            IProgress <double> progress = new Progress <double>(p =>
            {
                ExtensionMethods.SynchronizedInvoke(downloadQueueMaterialListView, () => downloadQueueMaterialListView.Items[_listViewItems].SubItems[4].Text = (p * 100).ToString("0.00") + "%");
                if (p * 100 == 100)
                {
                    ExtensionMethods.SynchronizedInvoke(downloadQueueMaterialListView, () => downloadQueueMaterialListView.Items[_listViewItems].SubItems[4].Text = "Done!");
                    DatabaseOperations.AddNewRecord(Settings.Default.Guid, title, format, savePath);

                    if (deleteDoneCheckBox.Checked == true)
                    {
                        Thread.Sleep(2000);
                        ExtensionMethods.SynchronizedInvoke(downloadQueueMaterialListView, () => downloadQueueMaterialListView.Items[_listViewItems].Remove());
                    }
                }
            });

            await Task.Run(() => _converter.DownloadAndProcessMediaStreamsAsync(_mediaStreamInfos, savePath + "." + format, format, progress));
        }
Ejemplo n.º 29
0
        public static bool DownloadVideoViaYoutubeExplode(string url, string successPath, string failurePath, TaskProgressReporter reporter)
        {
            try
            {
                reporter?.ReportInDeterminate("getting links");

                string             id            = YoutubeClient.ParseVideoId(url);
                YoutubeClient      client        = new YoutubeClient();
                MediaStreamInfoSet streamInfoSet = client.GetVideoMediaStreamInfosAsync(id).Result;

                MuxedStreamInfo streamInfo = streamInfoSet.Muxed.First(m => m.Container.GetFileExtension().ToLower() == "mp4");
                //string ext = streamInfo.Container.GetFileExtension();
                client.DownloadMediaStreamAsync(streamInfo, successPath, reporter == null
                    ? null
                    : new Progress <double>(d => reporter.ReportDeterminate((int)(d * 100), "downloading"))).Wait();
                return(true);
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception);
                File.Create(failurePath).Close();
                return(false);
            }
        }
Ejemplo n.º 30
0
 public VideoInfo(Video videoMetadata, MediaStreamInfoSet streamInfo)
 {
     this.VideoMetadata = videoMetadata;
     this.StreamInfo    = streamInfo;
 }