private IPicture ImageToIPicture(SpotifyAPI.Web.Models.Image image) { DownloadFileFromUri(image.Url, MyResources.Instance.TempPicPath); var picture = new Picture(new ByteVector((byte[])new ImageConverter() .ConvertTo(System.Drawing.Image.FromFile(MyResources.Instance.TempPicPath), typeof(byte[])))) { Type = PictureType.FrontCover, MimeType = "Cover" }; return(picture); }
public async Task DownloadTrack(MusixSongResult Track, string OutputDirectory, AudioEffectStack Effects = null, CancellationToken cancellationToken = default) { int Steps; int Step = 0; if (Effects == null) { Steps = 9; } else { Steps = 9 + Effects.EffectCount; } TryCallback(Step, Steps, "Starting Download", Track); if (cancellationToken.IsCancellationRequested) { return; } bool HasEffects = Effects != null; if (HasEffects) { Console.WriteLine("Has Effects"); if (string.IsNullOrEmpty(Effects.AudioCachePath)) { Effects.AudioCachePath = AudioCache; } } // Step 1 Step++; TryCallback(Step, Steps, "Preparing Download", Track); Console.WriteLine("Start Download"); if (!Track.HasVideo) { Console.WriteLine("No Vid"); } if (!Track.HasVideo) { return; } string SourceAudio = Path.Combine(AudioCache, $"audio_source_{DateTime.Now.Ticks}"); string AlbumCover = Path.Combine(ImageCachePath, $"cover_{DateTime.Now.Ticks}.jpg"); string OutputFile = Path.Combine(OutputDirectory, FileHelpers.ScrubFileName($"{Track.SpotifyTrack.Artists[0].Name} - {Track.SpotifyTrack.Name.Replace("?", "").Trim(' ')}.mp3")); string MidConversionFile = Path.Combine(AudioCache, FileHelpers.ScrubFileName($"MidConversion_{DateTime.Now.Ticks}.mp3")); // Step 2 Step++; TryCallback(Step, Steps, "Aquiring streams", Track); StreamManifest StreamData = await YouTube.Videos.Streams.GetManifestAsync(Track.YoutubeVideo.Id); if (cancellationToken.IsCancellationRequested) { return; } // Step 3 Step++; TryCallback(Step, Steps, "Sorting Streams", Track); List <AudioOnlyStreamInfo> AudioStreams = StreamData.GetAudioOnlyStreams().ToList(); AudioStreams.OrderBy(dat => dat.Bitrate); if (AudioStreams.Count() == 0) { Console.WriteLine("No Streams"); } if (AudioStreams.Count() == 0) { return; } IAudioStreamInfo SelectedStream = AudioStreams[0]; // Step 4 Step++; TryCallback(Step, Steps, "Starting downloads", Track); if (cancellationToken.IsCancellationRequested) { return; } //Task AudioDownloadTask = new Task(async () => await YouTube.Videos.Streams.DownloadAsync(SelectedStream, SourceAudio)); var req = WebRequest.CreateHttp(SelectedStream.Url); req.Method = "GET"; using (var resp = req.GetResponse()) using (var network = resp.GetResponseStream()) using (var fs = new FileStream(SourceAudio, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { Console.WriteLine("Downloading"); await network.CopyToAsync(fs); Console.WriteLine("flushing"); await fs.FlushAsync(); Console.WriteLine("done"); } WebClient WebCl = new WebClient(); Step++; TryCallback(Step, Steps, "Starting", Track); SpotifyImage Cover = Track.SpotifyTrack.Album.Images[0]; var CoverDownloadTask = new Task(() => { Console.WriteLine("Downloading Cover"); WebCl.DownloadFile(new Uri(Cover.Url), AlbumCover); } ); CoverDownloadTask.Start(); Step++; TryCallback(Step, Steps, "Waiting for downloads", Track); if (cancellationToken.IsCancellationRequested) { return; } //if (!AudioDownloadTask.IsCompleted) //{ // Console.WriteLine("Waiting on artwork..."); // CoverDownloadTask.Wait(); //} if (cancellationToken.IsCancellationRequested) { return; } //if (!AudioDownloadTask.IsCompleted) //{ // Console.WriteLine("Waiting on audio..."); // AudioDownloadTask.Wait(); // Console.WriteLine("Download Complete."); //} Thread.Sleep(100); if (cancellationToken.IsCancellationRequested) { return; } string ConversionFile = OutputFile; if (HasEffects) { ConversionFile = MidConversionFile; } if (File.Exists(OutputFile)) { File.Delete(OutputFile); } if (File.Exists(ConversionFile)) { File.Delete(ConversionFile); } Step++; TryCallback(Step, Steps, "Transcoding audio to mp3", Track); // Step 8 Console.WriteLine("Starting Conversion..."); await ConversionsProvider.Convert(SourceAudio, ConversionFile); Console.WriteLine("Conversion Complete."); // Step 9 if (cancellationToken.IsCancellationRequested) { return; } if (HasEffects) { Step++; int InternalStep = Step; TryCallback(Step, Steps, "Applying audio effects", Track); Effects.ApplyEffects(ConversionFile, OutputFile, (step, stepmax, status, download) => { step++; TryCallback(Step, Steps, status, Track); }, cancellationToken); } if (cancellationToken.IsCancellationRequested) { return; } Step++; TryCallback(Step, Steps, "Applying ID3 metadata tags", Track); // Step 10 TagLib.Id3v2.Tag.DefaultVersion = 3; TagLib.Id3v2.Tag.ForceDefaultVersion = true; TagLibFile TLF = TagLibFile.Create(OutputFile); TagLibPicture Pic = new TagLibPicture(AlbumCover); TagLib.Id3v2.AttachedPictureFrame Frame = new TagLib.Id3v2.AttachedPictureFrame(Pic) { MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg }; Pic.Type = TagLib.PictureType.FrontCover; TagLib.IPicture[] Pics = { Pic }; TLF.Tag.Pictures = Pics; TLF.Tag.Title = Track.SpotifyTrack.Name.Split('-')[0].Trim(' '); TLF.Tag.Album = Track.SpotifyTrack.Album.Name; TLF.Tag.AlbumArtists = Track.SpotifyTrack.Album.Artists.CastEnumerable(x => x.Name).ToArray(); TLF.Tag.Disc = (uint)Track.SpotifyTrack.DiscNumber; TLF.Tag.AlbumSort = Track.SpotifyTrack.Album.AlbumType; DateTime?DT = GetDate(Track.SpotifyTrack.Album.ReleaseDate); if (DT.HasValue) { TLF.Tag.Year = (uint)DT.Value.Year; } if (cancellationToken.IsCancellationRequested) { return; } TLF.Save(); // Clean Up // Step 11 Step++; TryCallback(Step, Steps, "Cleaning up", Track); WebCl.Dispose(); TLF.Dispose(); Console.WriteLine("Done."); OnMusixDownloadComplete?.Invoke(Track); }
private void DisplayRecommendation(KeyValuePair <string, List <FullTrack> > recommendation) { // Create container. FlowLayoutPanel articleContainer = new FlowLayoutPanel(); articleContainer.Size = new Size(SongDisplayPanel.Size.Width - 100, (128 * recommendation.Value.Count) + 250); // Disable horizontal scrolling. articleContainer.HorizontalScroll.Maximum = 0; articleContainer.AutoScroll = false; articleContainer.VerticalScroll.Visible = false; articleContainer.AutoScroll = true; articleContainer.WrapContents = false; articleContainer.BackColor = Color.FromArgb(76, 113, 131); articleContainer.FlowDirection = FlowDirection.TopDown; articleContainer.BorderStyle = BorderStyle.FixedSingle; // Create title label. Label articleTitleLabel = new Label(); articleTitleLabel.Text = $"Article: {recommendation.Key}"; articleTitleLabel.AutoSize = true; articleContainer.ForeColor = Color.White; articleTitleLabel.Font = new Font(FontFamily.GenericSansSerif, 32, FontStyle.Underline); articleTitleLabel.Top = 0; articleTitleLabel.Left = 0; articleTitleLabel.Margin = new Padding(3, 3, 3, 25); articleContainer.Controls.Add(articleTitleLabel); // Create list of songs. foreach (FullTrack song in recommendation.Value) { // Create song container. FlowLayoutPanel songContainer = new FlowLayoutPanel(); songContainer.Size = new Size(SongDisplayPanel.Size.Width - 110, 128); songContainer.FlowDirection = FlowDirection.LeftToRight; // Create the song name label, this displays the song title and artist. LinkLabel songNameLabel = new LinkLabel(); songNameLabel.Text = $"{song.Name} - {string.Join(", ", song.Artists.Select(a => a.Name))}"; songNameLabel.AutoSize = true; songNameLabel.LinkColor = Color.White; songNameLabel.Font = new Font(FontFamily.GenericSansSerif, 18); // If there are external URLs available, use the first one as the link to open the song. if (song.ExternUrls.Count > 0) { songNameLabel.Click += (sender, e) => Process.Start(song.ExternUrls.First().Value); } SpotifyAPI.Web.Models.Image art = song.Album.Images.FirstOrDefault(); // If there is album art, use it. if (art != default) { // Create a picture box and load the art from the provided URL. PictureBox albumArtBox = new PictureBox(); albumArtBox.Size = new Size(128, 128); albumArtBox.SizeMode = PictureBoxSizeMode.Zoom; albumArtBox.Load(art.Url); songContainer.Controls.Add(albumArtBox); } songContainer.Controls.Add(songNameLabel); articleContainer.Controls.Add(songContainer); } SongDisplayPanel.Controls.Add(articleContainer); }