public void TagTheMP3(string Filename, string _TrackName, string _Artist, string _Album, Bitmap _Artwork) { Busy = true; //Initialize Info if (_Album == _TrackName) { _Album = "Single"; } Bitmap TagArtwork = new Bitmap(_Artwork); TagLib.File TagFile = TagLib.File.Create(Filename); TagFile.Tag.Title = _TrackName; TagFile.Tag.Album = _Album; TagFile.Tag.Artists = new string[] { _Artist }; TagFile.Tag.Comment = "Ripped From Spotify By TheBitBrine's Spotify Recorder"; //Artwork Stuff TagLib.Picture TempArtwork = new TagLib.Picture(); TempArtwork.Type = TagLib.PictureType.FrontCover; TempArtwork.Description = "Cover"; TempArtwork.MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg; MemoryStream ms = new MemoryStream(); TagArtwork.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); ms.Position = 0; TempArtwork.Data = TagLib.ByteVector.FromStream(ms); TagFile.Tag.Pictures = new TagLib.IPicture[] { TempArtwork }; //Finally Write To File & Close Memory Stream TagFile.Save(); ms.Close(); Busy = false; }
/// <summary> /// Sets the cover image of the given song to the given Picture. Setting it to "null" should result in a deletion. /// </summary> /// <param name="Song"></param> /// <param name="newPicture"></param> public static void SetImage(this TagLib.File Song, TagLib.Picture newPicture) { if (newPicture != null) { if (Song.Tag.Pictures.FirstOrDefault() != newPicture) { TagLib.IPicture[] pic = new TagLib.IPicture[1]; pic[0] = newPicture; Song.Tag.Pictures = pic; } else { } } else { Console.WriteLine("YOOO"); Song.Tag.Pictures = new TagLib.IPicture[0]; } }
public Extractor(ProgressBar progressBar, Button buttonExtract, Button buttonOptions, Button buttonCancel) { ViewButtonOptions = buttonOptions; ViewButtonExtract = buttonExtract; ViewButtonCancel = buttonCancel; ViewPrBar = progressBar; BackgroundWorker1 = new BackgroundWorker(); BackgroundWorker1.DoWork += BackgroundWorker1_DoWork; BackgroundWorker1.ProgressChanged += BackgroundWorker1_ProgressChanged; BackgroundWorker1.RunWorkerCompleted += BackgroundWorker1_RunWorkerCompleted; BackgroundWorker1.WorkerReportsProgress = true; BackgroundWorker1.WorkerSupportsCancellation = true; Pic = new TagLib.Picture(); Pic.MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg; Pic.Description = "Cover"; foreach (PictureType pType in Enum.GetValues(typeof(PictureType))) { Pic.Type = pType; Pic.Data = null; } Pic.Type = TagLib.PictureType.FrontCover; PicDefault = new TagLib.Picture(); PicDefault.MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg; PicDefault.Description = "Cover"; foreach (PictureType pType in Enum.GetValues(typeof(PictureType))) { PicDefault.Type = pType; PicDefault.Data = null; } PicDefault.Type = TagLib.PictureType.FrontCover; }
/*[STAThread] static void Main() { if(!SoundCloudCore.Connect(new Login(user, pass, ClientID, ClientSecret))) return; var list = new List<int>(); for(var i = 0; i < Me.LikesCount; i += 10) { if(i >= Me.LikesCount) break; list = list.Concat(Me.GetLikedTracks(i, 10)).ToList(); Console.WriteLine("SEARCHING: " + i + "/" + Me.LikesCount); } Console.WriteLine("COMPLETED: " + list.Count + " / " + Me.LikesCount + "Track info was downloaded"); // Download all tracks to folder foreach(var id in list) DownloadTrack(SoundCloudCore.Tracks[id]); Directory.Delete("Images", true); Console.ReadLine(); }*/ static void DownloadTrack(Track track) { var wc = new WebClient(); if(!Directory.Exists("Tracks")) Directory.CreateDirectory("Tracks"); if(!Directory.Exists("Images")) Directory.CreateDirectory("Images"); var path = "Tracks\\" + track.Title + ".mp3"; if(System.IO.File.Exists(path)) return; try { wc.DownloadFile(new Uri(track.StreamUrl), path); // Write tag if(!System.IO.File.Exists(path)) return; var tag = TagLib.File.Create(path); tag.Tag.Title = track.Title; tag.Tag.BeatsPerMinute = (uint)track.Bpm; tag.Tag.Year = (uint)track.Created.Year; // Get track cover var imgPath = "Images\\" + track.Title + ".jpg"; wc.DownloadFile(new Uri(track.GetCover(AlbumSize.x300)), imgPath); if(System.IO.File.Exists(imgPath)) { var pic = new IPicture[1]; pic[0] = new Picture(imgPath); tag.Tag.Pictures = pic; } // Save tag info tag.Save(); Console.WriteLine("Downloaded track: " + track.Title); } catch(Exception ex) { Console.WriteLine("Error downloading track: " + track.Title + "; Exception: " + ex.Message); } }
private void ItemImage_Drop(object sender, System.Windows.DragEventArgs e) { try { var uiElement = sender as UIElement; if (uiElement == null) { return; } var item = uiElement.FindContainingListViewItem(); if (item == null) { return; } var track = item.DataContext as IOldTrack; if (track != null) { var image = e.Data.GetData(DataFormats.Bitmap) as System.Windows.Controls.Image; if (image != null) { return; } var html = e.Data.GetData(DataFormats.Html) as string; if (!string.IsNullOrEmpty(html)) { var regex = new System.Text.RegularExpressions.Regex("src=['\"](?<PATH>[^\"']+)"); var match = regex.Match(html); if (match != null) { var path = match.Groups["PATH"].Value; if (!string.IsNullOrEmpty(path)) { var request = System.Net.HttpWebRequest.Create(path); var response = request.GetResponse(); if (response != null) { using (var stream = response.GetResponseStream()) { var buffer = stream.ToBuffer(); var data = new ByteVector(buffer); var picture = new TagLib.Picture(data); tagController.AddPicture(track, picture); } } } } } } } catch (Exception ex) { log.Error("ItemImage_Drop", ex); } }
private IPicture GetPicture() { string path = @"..\..\..\lib\rockie200.jpg"; var picture = new Picture(path); byte[] content = System.IO.File.ReadAllBytes(path); using (var ms = new MemoryStream(content)) { picture.Data = TagLib.ByteVector.FromStream(ms); } return picture; }
private async void SetMetaData(int position, string title, string artist, ThumbnailSet thumbnails) { string filePath = queue[position].Path; await Task.Run(async() => { Stream stream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite); var meta = TagLib.File.Create(new StreamFileAbstraction(filePath, stream, stream)); meta.Tag.Title = title; meta.Tag.Performers = new string[] { artist }; meta.Tag.Album = title + " - " + artist; meta.Tag.Comment = queue[position].YoutubeID; IPicture[] pictures = new IPicture[1]; Bitmap bitmap = Picasso.With(this).Load(await YoutubeManager.GetBestThumb(thumbnails)).Transform(new RemoveBlackBorder(true)).MemoryPolicy(MemoryPolicy.NoCache).Get(); byte[] data; using (var MemoryStream = new MemoryStream()) { bitmap.Compress(Bitmap.CompressFormat.Png, 0, MemoryStream); data = MemoryStream.ToArray(); } bitmap.Recycle(); pictures[0] = new Picture(data); meta.Tag.Pictures = pictures; meta.Save(); stream.Dispose(); }); MediaScannerConnection.ScanFile(this, new string[] { filePath }, null, this); if (queue[position].PlaylistName == null) { queue[position].State = DownloadState.Completed; } else { queue[position].State = DownloadState.Playlist; } if (!queue.Exists(x => x.State == DownloadState.None || x.State == DownloadState.Downloading || x.State == DownloadState.Initialization || x.State == DownloadState.MetaData || x.State == DownloadState.Playlist)) { StopForeground(true); DownloadQueue.instance?.Finish(); queue.Clear(); } else { UpdateList(position); } }
public static void removeAllArtwork(ItunesLibrary lib) { TagLib.Picture pic = new TagLib.Picture(); foreach (KeyValuePair <string, Artist> artistEntry in lib.Artists) { foreach (KeyValuePair <string, Album> albumEntry in artistEntry.Value.Albums) { foreach (string path in albumEntry.Value.TrackPaths) { TagLib.File file = TagLib.File.Create(path); file.Tag.Pictures = null; file.Save(); } } } }
private static void CopyTags(Tag source, Tag target) { source.CopyTo(target, true); var l = source.Pictures.Length; var pictures = new IPicture[l]; for (var i = 0; i < source.Pictures.Length; i++) { pictures[i] = new Picture(source.Pictures[i].Data) { MimeType = source.Pictures[i].MimeType, Description = source.Pictures[i].Description, Type = source.Pictures[i].Type }; } target.Pictures = pictures; }
//Images private TagLib.IPicture getImage(String dic) { TagLib.IPicture icon; //= Properties.Resources.album; //Mp3File TagLib.File mp3 = TagLib.File.Create(dic); //Verify if cover if (mp3.Tag.Pictures.Length == 0) { TagLib.Picture pic = new TagLib.Picture("D:/Users/Gabo/Escritorio/Proyectos/Projects/Reproductor de Musica/Reproductor de Musica/Resources/descarga (4).jpg"); icon = pic; } else { icon = mp3.Tag.Pictures[0]; } return(icon); }
private static IPicture DownloadAlbumArt(Track reqTeack) { IPicture picture = null; var client = new RestClient(reqTeack.artwork_large); var response = client.DownloadData(new RestRequest(Method.GET)); if (response == null) { MessageBox.Show("Album art download failed", "An error occured", MessageBoxButton.OK); Environment.Exit(-1); /* picture = null; */ } else { picture = new Picture(new ByteVector(response)); } return picture; }
private static void ProcessDir(string rootDir, string coverImage) { var dir = Path.GetDirectoryName(coverImage); Picture picture = null; foreach (var mp3 in Directory.EnumerateFiles(dir, "*.mp3").Select(f => TagLib.File.Create(f))) { if (mp3.Tag.Pictures.Length == 0) { var displayName = mp3.Name.Substring(rootDir.Length + 1); Console.Out.WriteLine(displayName); if (picture == null) picture = new Picture(coverImage); mp3.Tag.Pictures = new[] { picture }; mp3.Save(); } } }
internal void Save() { // Remove All Old Artwork - not needed, this is done inside by _af.Tag.Pictures property List<Picture> pics = new List<Picture>(); foreach (PictureInfo pi in ArtworkImages) { MemoryStream ms = new MemoryStream(); Bitmap bmp = pi.Picture; const int MaxAPICFrameSize = 64 * 1024; // 64 kB bmp.Save(ms, ImageFormat.Png); while (ms.Length >= MaxAPICFrameSize) { Size sz = bmp.Size; sz.Width = (int)(sz.Width * 0.9); sz.Height = (int)(sz.Height * 0.9); bmp = new Bitmap(ImageProvider.ScaleImage(bmp, sz, false)); bmp.Save(ms, ImageFormat.Png); } Picture pic = new Picture(); pic.Data = new ByteVector(ms.GetBuffer()); pic.Description = pi.Description; pic.Type = pi.PictureType; pic.MimeType = "image/png"; pics.Add(pic); } if (pics.Count > 0) _af.Tag.Pictures = pics.ToArray(); else _af.Tag.Pictures = null; }
public static void ApplyTags(OutputMetadata tagdata, ProgressUpdate procprogress, AudioBookConverterMain _owner) { if (Owner.bgAACEncoder.CancellationPending) { return; } Owner = _owner; procprogress.CurrentFilename = "Writing MetaData"; procprogress.TotalFiles = 1; procprogress.CurrentFile = 1; procprogress.BentoWorking = true; Owner.bgAACEncoder.ReportProgress(0, procprogress); TagLib.File Mp4File = TagLib.File.Create(tagdata.OutputFile); if (tagdata.Album != null) { Mp4File.Tag.Album = tagdata.Album; } if (tagdata.AlbumSort != null) { Mp4File.Tag.AlbumSort = tagdata.AlbumSort; } if (tagdata.Composer != null) { Mp4File.Tag.Composers = tagdata.Composer.Split(';'); } if (tagdata.ComposerSort != null) { Mp4File.Tag.ComposersSort = tagdata.ComposerSort.Split(';'); } Mp4File.Tag.Disc = (uint)tagdata.Disc; Mp4File.Tag.DiscCount = (uint)tagdata.DiscTotal; Mp4File.Tag.Kind = 2; if (tagdata.Artist != null) { Mp4File.Tag.Performers = tagdata.Artist.Split(';'); } if (tagdata.ArtistSort != null) { Mp4File.Tag.PerformersSort = tagdata.ArtistSort.Split(';'); } if (tagdata.Title != null) { Mp4File.Tag.Title = tagdata.Title; } if (tagdata.TitleSort != null) { Mp4File.Tag.TitleSort = tagdata.TitleSort; } Mp4File.Tag.Track = (uint)tagdata.Track; Mp4File.Tag.Track = (uint)tagdata.TrackTotal; Mp4File.Tag.Year = (uint)tagdata.Year; if (tagdata.Comment != null) { Mp4File.Tag.Comment = tagdata.Comment; } if (tagdata.Image != null) { TagLib.Picture ipic = new TagLib.Picture(); TagLib.ByteVector picdata = new TagLib.ByteVector(); picdata.Add(tagdata.Image); ipic.Data = picdata; ipic.MimeType = "image/jpeg"; ipic.Type = PictureType.FrontCover; ipic.Description = "Front Cover"; Picture[] PictFrames = { ipic }; Mp4File.Tag.Pictures = PictFrames; } Mp4File.Save(); }
public void doMe(object num) { LastFMWorker last = (LastFMWorker)num; last.busy = true; int count = last.id; int arcount = last.orignial_index; try { XmlDocument xdoc; XmlNode node; double confidence; string artist; string title; string mbid; LastFmLib.API20.Types.TrackInformation tr; string cd = ""; ListViewItem item1; updateTdisplay(count, 4); string xmlsreing = HBPUID.GenUID.LastFM.Run(last.filename, 0).Trim(); updateTdisplay(count, 2); xdoc = new XmlDocument(); xdoc.LoadXml(xmlsreing); node = xdoc.SelectSingleNode("//lfm/tracks/track"); confidence = 0; double.TryParse(xdoc.SelectSingleNode("//lfm/tracks/track/@rank").InnerText, out confidence); confidence = confidence * 100; artist = node.SelectSingleNode("//track/artist/name").InnerText; title = node.SelectSingleNode("//track/name").InnerText; mbid = node.SelectSingleNode("//track/mbid").InnerText; string largim = null ; try { largim = xdoc.SelectNodes("//lfm/tracks/track/image").Item(3).InnerXml; } catch (Exception imagex) { } if (largim != null) { TagLib.File tfile; string localFilename = @"c:\temp.jpg"; using (WebClient client = new WebClient()) { client.DownloadFile(largim, localFilename); } tfile = TagLib.File.Create(last.filename); TagLib.Picture picture = new TagLib.Picture(localFilename); TagLib.Id3v2.AttachedPictureFrame albumCoverPictFrame = new TagLib.Id3v2.AttachedPictureFrame(picture); albumCoverPictFrame.MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg; albumCoverPictFrame.Type = TagLib.PictureType.FrontCover; TagLib.IPicture[] pictFrames = new IPicture[1]; pictFrames[0] = (IPicture)albumCoverPictFrame; tfile.Tag.Pictures = pictFrames; if (mbid != null) { tfile.Tag.MusicBrainzTrackId = mbid; } tfile.Save(); } item1 = new ListViewItem(confidence.ToString()); if (mbid.Length > 2) { tr = client.Track.GetInfo(new Guid(mbid)); } else { tr = client.Track.GetInfo(new LastFmLib.API20.Types.Track(artist, title)); //client.Track. } string tt1 = HttpGetTrackInfo("", artist, title, "868b33aa44239a11ebd04e58e7e484ff"); dynamic json = JValue.Parse(tt1); TagLib.File mp3file; mp3file = TagLib.File.Create(last.filename); try { if (json.track != null) { if (json.track.name != null) { mp3file.Tag.Title = (string)json.track.name; } if (json.track.mbid != null) { mp3file.Tag.MusicBrainzTrackId = (string)json.track.mbid; } if (json.track.url != null) { mp3file.Tag.Lyrics = (string)json.track.url; } if (json.track.album != null) { if (json.track.album.title != null) { mp3file.Tag.Album = (string)json.track.album.title; } if (json.track.album.mbid != null) { mp3file.Tag.MusicBrainzReleaseId = (string)json.track.album.mbid; } if (json.track.album.@attr != null) { if ([email protected] != null) { mp3file.Tag.Track = (uint)json.track.album.attr.position; } } } if (json.track.artist != null) { if (json.track.artist.name != null) { mp3file.Tag.AlbumArtists[0] = (string)json.track.artist.name; } if (json.track.artist.mbid != null) { mp3file.Tag.MusicBrainzArtistId = (string)json.track.artist.mbid; } } if (json.track.toptags != null) { if (json.track.toptags.tag != null) { if (json.track.toptags.tag[0].name != null) { mp3file.Tag.Genres[0] = (string)json.track.toptags.tag[0].name; } } } } } catch (Exception ex11) { } mp3file.Save(); //client.Album.Search( XmlDocument xdoc2 = new XmlDocument(); xdoc2.LoadXml("<xml>" + tr.innerxml + "</xml>"); try { string albumname; string track; albumname = xdoc2.SelectSingleNode("//album/title").InnerText; track = xdoc2.SelectSingleNode("//album/@position").InnerText; if (albumname != null) { cd = albumname; } else { TagLib.File tfile; tfile = TagLib.File.Create(last.filename); if (tfile.Tag.Album != null) { cd = tfile.Tag.Album; } } if (track != null) { } } catch (Exception ex) { //Album retrieval failed , lets load the old album back shall we TagLib.File tfile; tfile = TagLib.File.Create(last.filename); if (tfile.Tag.Album != null) { cd = tfile.Tag.Album; } } item1.SubItems.Add(title); item1.SubItems.Add(cd); item1.SubItems.Add(artist); this.mainC1.listView1.Invoke(new MethodInvoker(delegate { this.mainC1.listView1.Items[arcount].BackColor = Color.LightGray; this.progressBar1.Value += 1; double perc = ((this.progressBar1.Value * 100) / this.progressBar1.Maximum); this.label1.Text = perc.ToString() + " %"; string no = this.mainC1.listView1.Items[arcount].SubItems[4].Text; item1.SubItems.Add(no); item1.SubItems.Add(this.mainC1.listView1.Items[arcount].SubItems[0].Text); })); AddListBoxItem(item1); last.status = false; last.busy = false; doEndLast(last.id); } catch (Exception e1) { TagLib.File mp3file; mp3file = TagLib.File.Create(last.filename); Regex rgx = new Regex("[^a-zA-Z0-9'&(). -]"); bool gotart = false; bool gottrack = false; dynamic json = ""; try { string tt1 = HttpGetTrackInfo("", rgx.Replace(mp3file.Tag.AlbumArtists[0].ToString(), ""), rgx.Replace(mp3file.Tag.Title , "") , "868b33aa44239a11ebd04e58e7e484ff"); json = JValue.Parse(tt1); if (json.track != null) { if (json.track.name != null) { gotart = true; mp3file.Tag.Title = (string)json.track.name; } if (json.track.mbid != null) { mp3file.Tag.MusicBrainzTrackId = (string)json.track.mbid; } if (json.track.url != null) { mp3file.Tag.Lyrics = (string)json.track.url; } if (json.track.album != null) { if (json.track.album.title != null) { mp3file.Tag.Album = (string)json.track.album.title; } if (json.track.album.mbid != null) { mp3file.Tag.MusicBrainzReleaseId = (string)json.track.album.mbid; } if (json.track.album.@attr != null) { if ([email protected] != null) { mp3file.Tag.Track = (uint)json.track.album.attr.position; } } } if (json.track.artist != null) { if (json.track.artist.name != null) { gottrack = true; mp3file.Tag.AlbumArtists[0] = (string)json.track.artist.name; } if (json.track.artist.mbid != null) { mp3file.Tag.MusicBrainzArtistId = (string)json.track.artist.mbid; } } if (json.track.toptags != null) { if (json.track.toptags.tag != null) { if (json.track.toptags.tag[0].name != null) { mp3file.Tag.Genres[0] = (string)json.track.toptags.tag[0].name; } } } } } catch (Exception ex11) { } if (gottrack && gotart) { ListViewItem item1 = new ListViewItem("0"); item1.SubItems.Add((string)json.track.name); item1.SubItems.Add(mp3file.Tag.Album); item1.SubItems.Add((string)json.track.artist.name); this.mainC1.listView1.Invoke(new MethodInvoker(delegate { this.mainC1.listView1.Items[arcount].BackColor = Color.LightGray; this.progressBar1.Value += 1; double perc = ((this.progressBar1.Value * 100) / this.progressBar1.Maximum); this.label1.Text = perc.ToString() + " %"; string no = this.mainC1.listView1.Items[arcount].SubItems[4].Text; item1.SubItems.Add(no); item1.SubItems.Add(this.mainC1.listView1.Items[arcount].SubItems[0].Text); })); AddListBoxItem(item1); } else { this.mainC1.listView1.Invoke(new MethodInvoker(delegate { this.progressBar1.Value += 1; this.mainC1.listView1.Items[arcount].BackColor = Color.LightPink; double perc = ((this.progressBar1.Value * 100) / this.progressBar1.Maximum); this.label1.Text = perc.ToString() + " %"; })); } try { mp3file.Save(); } catch (Exception nex1) { } updateTdisplay(count, 3); last.status = false; last.busy = false; doEndLast(last.id); } }
public bool AddArtwork(string fp) { if (System.IO.File.Exists(fp)) { TagLib.Picture picture = new Picture(fp); TagLib.Id3v2.AttachedPictureFrame albumCoverPictFrame = new TagLib.Id3v2.AttachedPictureFrame(picture); albumCoverPictFrame.MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg; albumCoverPictFrame.Type = TagLib.PictureType.FrontCover; TagLib.IPicture[] pictFrames = new IPicture[1]; pictFrames[0] = (IPicture)albumCoverPictFrame; this.Tags.Pictures = pictFrames; DebugHelper.WriteLine(this.FileName + " --> embedded artwork"); return IsModified = true; } return false; }
public bool Guardar_Pista() { TagLib.File PistaMp3 = TagLib.File.Create(ruta); PistaMp3.Tag.Clear(); PistaMp3.Tag.Performers = new string[] { Artista }; PistaMp3.Tag.AlbumArtists = new string[] { Artista }; PistaMp3.Tag.Album = Album; PistaMp3.Tag.Year = (uint) Anyo; PistaMp3.Tag.Genres = new string[] { Genero }; PistaMp3.Tag.Comment = Comentario; PistaMp3.Tag.Title = Titulo; PistaMp3.Tag.Track = (uint)Indice; string rutaAuxiliar = Path.GetTempFileName(); caratulaAlbum.Save(rutaAuxiliar, System.Drawing.Imaging.ImageFormat.Jpeg); TagLib.Picture myCover = new Picture(rutaAuxiliar); //Coloco el Picture en el FrameCorrespondiente TagLib.Id3v2.AttachedPictureFrame coverAlbumArt = new TagLib.Id3v2.AttachedPictureFrame(myCover); //Seteo el tipo Mime coverAlbumArt.MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg; //Seteo el tipo de imagen que estoy colocando coverAlbumArt.Type = TagLib.PictureType.FrontCover; //Agrego el frame a la coleccion de imagenes que corresponde TagLib.IPicture[] pictFrame = { coverAlbumArt }; //Vuelco la coleccion de imagenes al Tag try { PistaMp3.Tag.Pictures = pictFrame; } catch { //MessageBox.Show("Imposible Insercion de Imagen en Tag. Posible Error de Archivo -" + new FileInfo(RutaArchivo).FullName + "-"); } System.IO.File.Delete(rutaAuxiliar); try { PistaMp3.Save(); PistaMp3.Dispose(); return true; } catch { PistaMp3.Dispose(); return false; } }
//Checks for artwork and applies to all ID3 data on all tracks for that album public void applyArtwork(DirectoryInfo albumDirs) { try { FileInfo picFile = new FileInfo(albumDirs.FullName + "\\" + "folder.jpg"); if (picFile.Exists) { Picture[] artwork = new Picture[1]; artwork[0] = Picture.CreateFromPath(albumDirs.FullName + "\\" + "folder.jpg"); foreach (FileInfo tracks in albumDirs.GetFiles("*.mp3")) { TagLib.File file = TagLib.File.Create(albumDirs.FullName + "\\" + tracks); file.Tag.Pictures = artwork; file.Save(); } } else { AppendTextBoxLine("Artwork not found at " + albumDirs.FullName + "\\" + "folder.jpg"); } } catch (Exception e) { AppendTextBoxLine("Couldn't find artwork at " + albumDirs.FullName + "\\" + "folder.jpg Exception: " + e); } }
async Task <bool> ValidateChanges(bool displayActionIfMountFail = false) { System.Console.WriteLine("&Validaing changes"); if (song.Title == title.Text && song.Artist == artist.Text && song.YoutubeID == youtubeID.Text && song.Album == album.Text && artURI == null) { return(true); } System.Console.WriteLine("&Requesting permission"); const string permission = Manifest.Permission.WriteExternalStorage; hasPermission = Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, permission) == (int)Permission.Granted; if (!hasPermission) { string[] permissions = new string[] { permission }; RequestPermissions(permissions, RequestCode); while (!hasPermission) { await Task.Delay(1000); } } if (!Environment.MediaMounted.Equals(Environment.GetExternalStorageState(new Java.IO.File(song.Path)))) { Snackbar snackBar = Snackbar.Make(FindViewById <CoordinatorLayout>(Resource.Id.snackBar), Resource.String.mount_error, Snackbar.LengthLong); snackBar.View.FindViewById <TextView>(Resource.Id.snackbar_text).SetTextColor(Color.White); if (displayActionIfMountFail) { snackBar.SetAction(Resource.String.mount_error_action, (v) => { Finish(); }); } snackBar.Show(); return(false); } try { System.Console.WriteLine("&Creating write stream"); Stream stream = new FileStream(song.Path, FileMode.Open, FileAccess.ReadWrite); var meta = TagLib.File.Create(new StreamFileAbstraction(song.Path, stream, stream)); System.Console.WriteLine("&Writing tags"); meta.Tag.Title = title.Text; song.Title = title.Text; meta.Tag.Performers = new string[] { artist.Text }; song.Artist = artist.Text; meta.Tag.Album = album.Text; song.Album = album.Text; meta.Tag.Comment = youtubeID.Text; if (queuePosition != -1 && MusicPlayer.queue.Count > queuePosition) { MusicPlayer.queue[queuePosition] = song; Player.instance?.RefreshPlayer(); Queue.instance.NotifyItemChanged(queuePosition); } if (ytThumbUri != null) { System.Console.WriteLine("&Writing YT Thumb"); await Task.Run(() => { IPicture[] pictures = new IPicture[1]; Bitmap bitmap = Picasso.With(Application.Context).Load(ytThumbUri).Transform(new RemoveBlackBorder(true)).Get(); byte[] data; using (var MemoryStream = new MemoryStream()) { bitmap.Compress(Bitmap.CompressFormat.Png, 0, MemoryStream); data = MemoryStream.ToArray(); } bitmap.Recycle(); pictures[0] = new Picture(data); meta.Tag.Pictures = pictures; ytThumbUri = null; }); } else if (artURI != null) { System.Console.WriteLine("&Writing ArtURI"); IPicture[] pictures = new IPicture[1]; Bitmap bitmap = null; if (tempFile) { await Task.Run(() => { bitmap = Picasso.With(this).Load(artURI).Transform(new RemoveBlackBorder(true)).Get(); }); } else { await Task.Run(() => { bitmap = Picasso.With(this).Load(artURI).Get(); }); } MemoryStream memoryStream = new MemoryStream(); bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, memoryStream); byte[] data = memoryStream.ToArray(); pictures[0] = new Picture(data); meta.Tag.Pictures = pictures; if (!tempFile) { artURI = null; } ContentResolver.Delete(ContentUris.WithAppendedId(Android.Net.Uri.Parse("content://media/external/audio/albumart"), song.AlbumArt), null, null); } System.Console.WriteLine("&Saving"); meta.Save(); stream.Dispose(); } catch (System.Exception e) { Toast.MakeText(this, Resource.String.format_unsupported, ToastLength.Long).Show(); System.Console.WriteLine("&EditMetadata Validate exception: (probably due to an unsupported format) - " + e.Message); } System.Console.WriteLine("&Deleting temp file"); if (tempFile) { tempFile = false; System.IO.File.Delete(artURI.Path); artURI = null; } System.Console.WriteLine("&Scanning file"); await Task.Delay(10); Android.Media.MediaScannerConnection.ScanFile(this, new string[] { song.Path }, null, null); Toast.MakeText(this, Resource.String.changes_saved, ToastLength.Short).Show(); return(true); }
public void MusicTags(int num, int session) { PassArguments result = songArray[session][num]; try { //===edit tags==== TagLib.File f = TagLib.File.Create(_dir + escapeFilename(result.PassedFileName) + ".mp3"); f.Tag.Clear(); f.Tag.AlbumArtists = new string[1] { result.PassedArtist }; f.Tag.Performers = new string[1] { result.PassedArtist }; f.Tag.Title = result.PassedSong; f.Tag.Album = result.PassedAlbum; // // Log(result.passedFileName + " and " + result.passedAlbumID); Image currentImage = GetAlbumArt(num, session); Picture pic = new Picture(); pic.Type = PictureType.FrontCover; pic.MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg; pic.Description = "Cover"; MemoryStream ms = new MemoryStream(); currentImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); // <-- Error doesn't occur anymore ms.Position = 0; pic.Data = ByteVector.FromStream(ms); f.Tag.Pictures = new IPicture[1] { pic }; f.Save(); ms.Close(); } catch (Exception ex) { Log("[Error: x7] " + ex.Message + Environment.NewLine + Environment.NewLine + result.PassedFileName, true); } }
/// <summary> /// Save an album to the music folder /// </summary> void saveAlbum() { try { Enable(false); // Need Media Foundation Api for encoding NAudio.MediaFoundation.MediaFoundationApi.Startup(); // Folder for artist string folder = Path.Combine(Properties.Settings.Default.MusicFolder, filename(Program.Album.Artist)); Directory.CreateDirectory(folder); // Folder under that for album folder = Path.Combine(folder, filename(Program.Album.Title)); Directory.CreateDirectory(folder); float start = 0; // Where track starts // Artist names separated by commas, not & string artist = Program.Album.Artist.Replace(" & ", ",").Replace(" and ", ","); for (int t = 0; t < Program.Album.Tracks.Count; t++) { Track trk = Program.Album.Tracks[t]; start += trk.Gap; string name = trk.Title; // Filename for track string dest = Path.Combine(folder, string.Format("{0:00} - {1}", t + 1, filename(name))) + Properties.Settings.Default.OutputType; Status("Saving {0} {1}", t + 1, name); ExtractWaveProvider p = new ExtractWaveProvider(m_Reader, start, trk.LengthSeconds); switch (Properties.Settings.Default.OutputType) { case ".wma": MediaFoundationEncoder.EncodeToWma(p, dest); break; case ".mp3": MediaFoundationEncoder.EncodeToMp3(p, dest); break; } // Album art picture, in TagLib format, to add to all tracks Picture pic = null; if (Program.Album.Art != null) { // Also save as AlbumArtLarge.jpg string path = Path.Combine(folder, "AlbumArtLarge.jpg"); Program.Album.Art.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg); pic = new Picture(path); pic.Type = PictureType.FrontCover; } using (TagLib.File d = TagLib.File.Create(dest)) { d.Tag.Album = Program.Album.Title; d.Tag.AlbumArtists = split(artist, ""); d.Tag.Performers = split(trk.Artist, artist); d.Tag.Genres = split(Program.Album.Genre, ""); d.Tag.Title = name; d.Tag.Track = (uint)t + 1; d.Tag.Year = Program.Album.Year; // Must do publisher, or Media Player will screw it up // but TagLib-sharp does not support it directly yet switch (Properties.Settings.Default.OutputType) { case ".wma": (d.Tag as TagLib.Asf.Tag).SetDescriptorString(Program.Album.Publisher, "WM/Publisher"); break; case ".mp3": (d.Tag as TagLib.Id3v2.Tag).SetTextFrame("TPUB", Program.Album.Publisher); break; } if (pic != null) d.Tag.Pictures = new Picture [] { pic}; d.Save(); } } Status("Save complete"); } finally { NAudio.MediaFoundation.MediaFoundationApi.Shutdown(); Enable(true); } }
private void ItemImage_Drop(object sender, System.Windows.DragEventArgs e) { try { var uiElement = sender as UIElement; if (uiElement == null) return; var item = uiElement.FindContainingListViewItem(); if (item == null) return; var track = item.DataContext as IOldTrack; if (track != null) { var image = e.Data.GetData(DataFormats.Bitmap) as System.Windows.Controls.Image; if (image != null) { return; } var html = e.Data.GetData(DataFormats.Html) as string; if (!string.IsNullOrEmpty(html)) { var regex = new System.Text.RegularExpressions.Regex("src=['\"](?<PATH>[^\"']+)"); var match = regex.Match(html); if (match != null) { var path = match.Groups["PATH"].Value; if (!string.IsNullOrEmpty(path)) { var request = System.Net.HttpWebRequest.Create(path); var response = request.GetResponse(); if (response != null) { using (var stream = response.GetResponseStream()) { var buffer = stream.ToBuffer(); var data = new ByteVector(buffer); var picture = new TagLib.Picture(data); tagController.AddPicture(track, picture); } } } } } } } catch (Exception ex) { log.Error("ItemImage_Drop", ex); } }
public void SaveFiles() { var task = MP3Files.ToObservable() .ForEachAsync(x => { var tag = x.GetTag(TagTypes.Id3v2, true) as ID3v2.Tag; var pic = new Picture(ImageSource); foreach (var p in tag.Pictures) { tag.RemoveFrame(p as ID3v2.Frame); } tag.AddFrame(new ID3v2.AttachedPictureFrame(pic)); x.Save(); }); task.ContinueWith( t => Messenger.RaiseAsync(new InformationMessage("An error occurred while saving file.", "Error", MessageBoxImage.Error, "Info")), TaskContinuationOptions.OnlyOnFaulted); task.ContinueWith( t => Messenger.RaiseAsync(new InformationMessage("Setting of the image was completed.", "Complete", MessageBoxImage.Information, "Info")), TaskContinuationOptions.OnlyOnRanToCompletion); }
public virtual IPicture GetPicture() { using (File file = File.Create(Path)) { var picture = file.Tag.Pictures.FirstOrDefault(); if (picture == null) { string[] extensions = { ".jpg", ".jpeg", ".png" }; string[] fileNames = {"folder", "cover"}; FileInfo info = new FileInfo(Path); if (info.Directory != null) { var files = Directory.EnumerateFiles(info.Directory.FullName, "*", SearchOption.TopDirectoryOnly); var imageFiles = files.Where(s => extensions .Any(ext => { FileInfo fileInfo = new FileInfo(s); return String.Compare(ext, fileInfo.Extension, StringComparison.OrdinalIgnoreCase) == 0; })); var imageCoverFiles = imageFiles.Where(s => fileNames.Any(name => { FileInfo imageInfo = new FileInfo(s); return imageInfo.Name.StartsWith(name, StringComparison.OrdinalIgnoreCase); })).ToArray(); if (imageCoverFiles.Any()) picture = new Picture(imageCoverFiles.First()); } } return picture; } }
public void AddArtwork(Image img) { MemoryStream ms = new MemoryStream(); img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] myBytes = ms.ToArray(); ByteVector byteVector = new ByteVector(myBytes, myBytes.Length); TagLib.Picture picture = new Picture(byteVector); TagLib.Id3v2.AttachedPictureFrame albumCoverPictFrame = new TagLib.Id3v2.AttachedPictureFrame(picture); albumCoverPictFrame.MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg; albumCoverPictFrame.Type = TagLib.PictureType.FrontCover; this.Tags.Pictures = new IPicture[1] { (IPicture)albumCoverPictFrame }; DebugHelper.WriteLine(this.FileName + " --> embedded artwork"); IsModified = true; }
private bool WriteMp3Metadata() { using (TagLib.File file = TagLib.File.Create(_filepath, "taglib/mp3", ReadStyle.Average)) { var tags = (Tag)file.GetTag(TagTypes.Id3v2); if (_coverBytes.Length > 0) { var byteVector = new ByteVector(_coverBytes); var coverPicture = new Picture { Description = "Cover", Data = byteVector, MimeType = MediaTypeNames.Image.Jpeg, Type = PictureType.FrontCover }; var attachedPictureFrame = new AttachedPictureFrame(coverPicture); tags.Pictures = new IPicture[] { attachedPictureFrame }; } tags.AddFrame(MetadataHelpers.BuildTextInformationFrame("TMED", "Digital Media")); if (_trackInfo?.TrackTags != null) { tags.Title = _trackInfo.TrackTags.Title; tags.Performers = _trackInfo.TrackTags.Artists.Select(x => x.Name).ToArray(); tags.AlbumArtists = _albumInfo.AlbumTags.Artists.Select(x => x.Name).ToArray(); // i don't like just using ART_NAME as the only album artist tags.Composers = _trackInfo.TrackTags.Contributors.Composers; if (_trackInfo.TrackTags.TrackNumber != null) { tags.Track = uint.Parse(_trackInfo.TrackTags.TrackNumber); } if (_trackInfo.TrackTags.DiscNumber != null) { tags.Disc = uint.Parse(_trackInfo.TrackTags.DiscNumber); } if (_trackInfo.TrackTags.Bpm != null) { string bpm = _trackInfo.TrackTags.Bpm; if (double.TryParse(bpm, out double bpmParsed)) { bpmParsed = Math.Round(bpmParsed); bpm = bpmParsed.ToString(CultureInfo.InvariantCulture); } tags.BeatsPerMinute = uint.Parse(bpm); } tags.AddFrame(MetadataHelpers.BuildTextInformationFrame("TSRC", _trackInfo.TrackTags.Isrc)); tags.AddFrame(MetadataHelpers.BuildTextInformationFrame("TPUB", _trackInfo.TrackTags.Contributors.Publishers)); tags.AddFrame(MetadataHelpers.BuildTextInformationFrame("TLEN", _trackInfo.TrackTags.Length)); tags.AddFrame(MetadataHelpers.BuildUserTextInformationFrame("EXPLICIT", _trackInfo.TrackTags.ExplicitLyrics)); tags.AddFrame(MetadataHelpers.BuildUserTextInformationFrame("REPLAYGAIN_TRACK_GAIN", _trackInfo.TrackTags.Gain)); tags.AddFrame(MetadataHelpers.BuildUserTextInformationFrame("WRITERS", _trackInfo.TrackTags.Contributors.Writers)); tags.AddFrame(MetadataHelpers.BuildUserTextInformationFrame("AUTHORS", _trackInfo.TrackTags.Contributors.Authors)); tags.AddFrame(MetadataHelpers.BuildUserTextInformationFrame("TIPL", "PRODUCERS", _trackInfo.TrackTags.Contributors.Publishers)); tags.AddFrame(MetadataHelpers.BuildUserTextInformationFrame("TIPL", "ENGINEERS", _trackInfo.TrackTags.Contributors.Engineers)); tags.AddFrame(MetadataHelpers.BuildUserTextInformationFrame("TIPL", "MIXERS", _trackInfo.TrackTags.Contributors.Mixers)); } if (_albumInfo?.AlbumTags != null) { tags.Album = _albumInfo.AlbumTags.Title; tags.Genres = _albumInfo.AlbumTags.Genres.GenreData.Select(x => x.Name).ToArray(); if (_albumInfo.AlbumTags.NumberOfTracks != null) { tags.TrackCount = uint.Parse(_albumInfo.AlbumTags.NumberOfTracks); } if (_albumInfo.AlbumTags.NumberOfDiscs != null) { tags.DiscCount = uint.Parse(_albumInfo.AlbumTags.NumberOfDiscs); } if (_albumInfo.AlbumTags.Type == "Compilation" || _albumInfo.AlbumTags.Type == "Playlist") { tags.IsCompilation = true; } tags.Copyright = _albumInfo.AlbumTags.Copyright; string year = _albumInfo.AlbumTags.ReleaseDate; if (!string.IsNullOrWhiteSpace(year)) { string[] yearSplit = year.Split("-"); if (yearSplit[0].Length == 4 && uint.TryParse(yearSplit[0], out uint yearParsed)) { tags.Year = yearParsed; } } tags.AddFrame(MetadataHelpers.BuildTextInformationFrame("TPUB", _albumInfo.AlbumTags.Label)); tags.AddFrame(MetadataHelpers.BuildTextInformationFrame("TDOR", _albumInfo.AlbumTags.ReleaseDate)); tags.AddFrame(MetadataHelpers.BuildUserTextInformationFrame("UPC", _albumInfo.AlbumTags.Upc)); } if (_trackInfo?.Lyrics != null) { tags.Lyrics = _trackInfo.Lyrics.UnSyncedLyrics; WriteLyricsFile(); } try { file.Save(); } catch (IOException ex) { Console.WriteLine(ex.Message); return(false); } } return(true); }
private Tag GetId3Tag() { var uri = new Uri(String.Format("https://gdata.youtube.com/feeds/api/videos/{0}?v=2", _youtubeEntry.YoutubeUrl.Id)); var tag = new Tag { Title = _youtubeEntry.Title, Album = _youtubeEntry.ChannelName }; try { var xml = new XmlDocument(); var req = WebRequest.Create(uri); using (var resp = req.GetResponse()) { using (var stream = resp.GetResponseStream()) { if (stream != null) xml.Load(stream); } } if (xml.DocumentElement != null) { var manager = new XmlNamespaceManager(xml.NameTable); manager.AddNamespace("root", "http://www.w3.org/2005/Atom"); manager.AddNamespace("app", "http://www.w3.org/2007/app"); manager.AddNamespace("media", "http://search.yahoo.com/mrss/"); manager.AddNamespace("gd", "http://schemas.google.com/g/2005"); manager.AddNamespace("yt", "http://gdata.youtube.com/schemas/2007"); tag.Title = GetText(xml, "media:group/media:title", manager); tag.Lyrics = "MS.Video.Downloader\r\n" + GetText(xml, "media:group/media:description", manager); tag.Copyright = GetText(xml, "media:group/media:license", manager); tag.Album = _youtubeEntry.ChannelName; tag.Composers = new[] { "MS.Video.Downloader", "Youtube", GetText(xml, "root:link[@rel=\"alternate\"]/@href", manager), GetText(xml, "root:author/root:name", manager), GetText(xml, "root:author/root:uri", manager) }; var urlNodes = xml.DocumentElement.SelectNodes("media:group/media:thumbnail", manager); var webClient = new WebClient(); var pics = new List<IPicture>(); if (urlNodes != null && urlNodes.Count > 0) { foreach (XmlNode urlNode in urlNodes) { var attributes = urlNode.Attributes; if (attributes == null || attributes.Count <= 0) continue; var url = attributes["url"]; if (url == null || String.IsNullOrEmpty(url.Value)) continue; var data = webClient.DownloadData(url.Value); IPicture pic = new Picture(new ByteVector(data)); pics.Add(pic); } } tag.Pictures = pics.ToArray(); } } catch { } return tag; }
public void AddPicture(IOldTrack track, string path) { var picture = new TagLib.Picture(path); AddPicture(track, picture); }
/// <summary> /// 下载线程 /// </summary> private void _Download() { while (downloadlist.Count != 0) { downloadlist[0].State = "正在下载音乐"; if (downloadlist[0].Url == null) { downloadlist[0].State = "无版权"; UpdateDownloadPage(); downloadlist.RemoveAt(0); continue; } UpdateDownloadPage(); string savepath = ""; string filename = "";; switch (setting.SaveNameStyle) { case 0: if (downloadlist[0].Url.IndexOf("flac") != -1) { filename = NameCheck(downloadlist[0].Title) + " - " + NameCheck(downloadlist[0].Singer) + ".flac"; } else { filename = NameCheck(downloadlist[0].Title) + " - " + NameCheck(downloadlist[0].Singer) + ".mp3"; } break; case 1: if (downloadlist[0].Url.IndexOf("flac") != -1) { filename = NameCheck(downloadlist[0].Singer) + " - " + NameCheck(downloadlist[0].Title) + ".flac"; } else { filename = NameCheck(downloadlist[0].Singer) + " - " + NameCheck(downloadlist[0].Title) + ".mp3"; } break; } switch (setting.SavePathStyle) { case 0: savepath = setting.SavePath; break; case 1: savepath = setting.SavePath + "\\" + NameCheck(downloadlist[0].Singer); break; case 2: savepath = setting.SavePath + "\\" + NameCheck(downloadlist[0].Singer) + "\\" + NameCheck(downloadlist[0].Album); break; } if (Directory.Exists(savepath)) { Directory.CreateDirectory(savepath); } if (downloadlist[0].IfDownloadMusic) { if (System.IO.File.Exists(savepath + "\\" + filename)) { downloadlist[0].State = "音乐已存在"; UpdateDownloadPage(); } else { using (WebClient wc = new WebClient()) { try { wc.DownloadFile(downloadlist[0].Url, savepath + "\\" + filename); } catch { downloadlist[0].State = "音乐下载错误"; downloadlist.RemoveAt(0); UpdateDownloadPage(); continue; } } } } if (downloadlist[0].IfDownloadLrc) { downloadlist[0].State = "正在下载歌词"; UpdateDownloadPage(); using (WebClient wc = new WebClient()) { try { if (downloadlist[0].Api == 1) { string savename = savepath + "\\" + filename.Replace(".flac", ".lrc").Replace(".mp3", ".lrc"); StreamReader sr = new StreamReader(wc.OpenRead(downloadlist[0].LrcUrl)); NeteaseLrc.Root lrc = JsonConvert.DeserializeObject <NeteaseLrc.Root>(sr.ReadToEnd()); StreamWriter sw = new StreamWriter(savename); sw.Write(lrc.lrc.lyric); sw.Flush(); sw.Close(); } else if (downloadlist[0].Api == 2) { string savename = savepath + "\\" + filename.Replace(".flac", ".lrc").Replace(".mp3", ".lrc"); StreamReader sr = new StreamReader(wc.OpenRead(downloadlist[0].LrcUrl)); QQLrc.Root lrc = JsonConvert.DeserializeObject <QQLrc.Root>(sr.ReadToEnd()); StreamWriter sw = new StreamWriter(savename); sw.Write(lrc.data.lrc); sw.Flush(); sw.Close(); } } catch { downloadlist[0].State = "歌词下载错误"; UpdateDownloadPage(); } } } if (downloadlist[0].IfDownloadPic) { downloadlist[0].State = "正在下载图片"; UpdateDownloadPage(); using (WebClient wc = new WebClient()) { try { wc.DownloadFile(downloadlist[0].PicUrl, savepath + "\\" + filename.Replace(".flac", ".jpg").Replace(".mp3", ".jpg")); } catch { downloadlist[0].State = "图片下载错误"; UpdateDownloadPage(); } } } try { if (filename.IndexOf(".mp3") != -1) { var tfile = TagLib.File.Create(savepath + "\\" + filename); tfile.Tag.Title = downloadlist[0].Title; tfile.Tag.Performers = new string[] { downloadlist[0].Singer }; tfile.Tag.Album = downloadlist[0].Album; if (downloadlist[0].IfDownloadPic && System.IO.File.Exists(savepath + "\\" + filename.Replace(".flac", "").Replace(".mp3", "") + ".jpg")) { TagLib.Picture pic = new TagLib.Picture(); pic.Type = TagLib.PictureType.FrontCover; pic.Description = "Cover"; pic.MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg; pic.Data = TagLib.ByteVector.FromPath(savepath + "\\" + filename.Replace(".flac", "").Replace(".mp3", "") + ".jpg"); tfile.Tag.Pictures = new TagLib.IPicture[] { pic }; } tfile.Save(); } else { var tfile = TagLib.Flac.File.Create(savepath + "\\" + filename); tfile.Tag.Title = downloadlist[0].Title; tfile.Tag.Performers = new string[] { downloadlist[0].Singer }; tfile.Tag.Album = downloadlist[0].Album; if (downloadlist[0].IfDownloadPic && System.IO.File.Exists(savepath + "\\" + filename.Replace(".flac", "").Replace(".mp3", "") + ".jpg")) { TagLib.Picture pic = new TagLib.Picture(); pic.Type = TagLib.PictureType.FrontCover; pic.Description = "Cover"; pic.MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg; pic.Data = TagLib.ByteVector.FromPath(savepath + "\\" + filename.Replace(".flac", "").Replace(".mp3", "") + ".jpg"); tfile.Tag.Pictures = new TagLib.IPicture[] { pic }; } tfile.Save(); } } catch { } downloadlist[0].State = "下载完成"; UpdateDownloadPage(); downloadlist.RemoveAt(0); } }
private void saveArtWorkWorker(IEnumerable<string> files, Image artwork, int jobID) { if (artwork == null || artwork.Width == 0 || artwork.Height == 0) { jCon.Jobs.Tables[Fields.Tracks].Rows[jobID][Fields.Process] = false; return; } if (chkResize.Checked && (artwork.Width > numSize.Value || artwork.Height > numSize.Value)) { artwork = Images.ResizeImage(artwork, new Size((int)numSize.Value, (int)numSize.Value)); } if (chkCrop.Checked) artwork = Images.CropImage(artwork); var stream = new MemoryStream(); artwork.Save(stream, ImageFormat.Jpeg); var buffer = new ByteVector(stream.ToArray()); var pic = new Picture(buffer); Picture[] artworkFrame = { pic }; foreach (var file in files) { var track = TagLib.File.Create(file); track.Tag.Pictures = artworkFrame; try { track.Save(); } catch (Exception e) { MessageBox.Show(e.Message); } } jCon.SetJobIsDone(jobID); }