private TagLib.IPicture WriteArtwork(IITTrack track, IITArtwork artwork) { string suffix; // ReSharper disable once SwitchStatementMissingSomeCases switch (artwork.Format) { case ITArtworkFormat.ITArtworkFormatBMP: suffix = ".bmp"; break; case ITArtworkFormat.ITArtworkFormatJPEG: suffix = ".jpg"; break; case ITArtworkFormat.ITArtworkFormatPNG: suffix = ".png"; break; default: suffix = ".jpg"; break; } var temp = Path.GetTempPath() + GetPersistentId(track) + suffix; if (File.Exists(temp)) { File.Delete(temp); } artwork.SaveArtworkToFile(temp); TagLib.IPicture picture = new TagLib.Picture(temp); File.Delete(temp); return(picture); }
public void SetArtwork(byte[] artworkData) { if (File.Exists(FileName)) { try { var mediaFileStream = TagLib.File.Create(FileName); if (mediaFileStream.Tag.Pictures != null) { TagLib.Picture pic = new TagLib.Picture( ); pic.Data = artworkData; // mediaFileStream.Tag.Pictures [ 0 ] = pic; TagLib.IPicture newArt = new TagLib.Picture( ); newArt.Data = artworkData; mediaFileStream.Tag.Pictures = new TagLib.IPicture [1] { newArt }; } else { mediaFileStream.Tag.Pictures = new TagLib.IPicture[1]; mediaFileStream.Tag.Pictures [0].Data = artworkData; } mediaFileStream.Save( ); } catch (Exception ex) { System.Windows.MessageBox.Show(ex.Message + System.Environment.NewLine + ex.StackTrace); } } }
public void ApplyMetadata(string file, string[] metadata, bool save, bool setImage) { TagLib.File musicFile = TagLib.File.Create(file); musicFile.Tag.Title = metadata[0]; musicFile.Tag.Performers = new string[] { metadata[1] }; musicFile.Tag.Comment += metadata[2] + metadata[3]; if (setImage) { TagLib.IPicture[] pictures = new TagLib.IPicture[musicFile.Tag.Pictures.Length + 1]; try { for (int i = 1; i <= musicFile.Tag.Pictures.Length; i++) //add the pictures already present in the music file { pictures[i] = musicFile.Tag.Pictures[i - 1]; } pictures[0] = new TagLib.Picture(metadata[4]); musicFile.Tag.Pictures = pictures; } catch (Exception PictureException) { MessageBox.Show(String.Format("There was an issue setting the image. {0}", PictureException.Message), file); } } if (save) { musicFile.Save(); } }
private void ApplyID3Tags(string fileName, string trackTitle, string[] artists, string album, Uri albumArt = null) { TagLib.File file = TagLib.File.Create(fileName); file.Tag.Title = trackTitle; file.Tag.Performers = artists; file.Tag.Album = album; if (albumArt != null) { string albumArtPath = GetMusicDirectory() + @"\" + Extensions.RemoveInvalidChars(artists.First()) + "_" + Extensions.RemoveInvalidChars(trackTitle) + "@large.jpg"; WebClient webClient = new WebClient(); webClient.DownloadFile(albumArt, albumArtPath); TagLib.IPicture coverArt = new TagLib.Picture(albumArtPath) { Type = TagLib.PictureType.FrontCover, Description = "Cover", MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg }; file.Tag.Pictures = new TagLib.IPicture[1] { coverArt }; FileInfo artInfo = new FileInfo(albumArtPath); artInfo.Delete(); } file.Save(); WriteDebug("ID3 tags saved to file."); }
/// <summary> /// Adds album art to a list of songs /// </summary> /// <param name="url">URL of album art</param> /// <param name="songs">List of songs located on the album that will have the artwork added</param> public void addArt(List <Art> urls, int index, List <Song> songs, bool isDownloaded, int workingIndex) { String name = Tools.getWildCardName(songs[0]); try { if (!isDownloaded) { new WebClient().DownloadFile(urls[index].url, name + ".jpg"); } w.setAlbumProgress(workingIndex, 70); //Use working index int progressTicker = 0; foreach (Song s in songs) { TagLib.File f = TagLib.File.Create(s.path); TagLib.IPicture newArt = new TagLib.Picture(name + ".jpg"); f.Tag.Pictures = new TagLib.IPicture[1] { newArt }; f.Save(); progressTicker++; double progress = (double)progressTicker / songs.Count * 30; w.setAlbumProgress(workingIndex, (int)progress); } } catch (Exception ex) { if (ex is WebException) { if (ex.InnerException is IOException) { addArt(urls, index, songs, true, workingIndex); } else { if ((ex as WebException).Status == WebExceptionStatus.ProtocolError) { if (index == urls.Count - 1) { throw; } addArt(urls, index + 1, songs, false, workingIndex); } else { throw; } } //Adding some funcitonality later } else { throw; //MessageBox.Show("Something went wrong.\n" + ex.Message); } } }
private void btnBrowseSong_Click(object sender, EventArgs e) { OpenFileDialog open = new OpenFileDialog { Filter = "JPEG Files|*.jpeg" /*+ "|All Files|*.*"*/ }; if (open.ShowDialog() == DialogResult.OK) { Image currentImage = new Bitmap(open.FileName); TagLib.Picture pic = new TagLib.Picture { Type = TagLib.PictureType.FrontCover, Description = "Cover", MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg }; currentImage.Save(_ms, System.Drawing.Imaging.ImageFormat.Jpeg); _ms.Position = 0; pic.Data = TagLib.ByteVector.FromStream(_ms); _file.Tag.Pictures = new TagLib.IPicture[] { pic }; this.picAlbum.Image = new Bitmap(currentImage, this.picAlbum.Size); } }
public static void getAvatarImg(ref TagLib.File tagFile, ref JsonPoco.Track song) { //download user profile avatar image string avatarFilepath = Path.GetTempFileName(); string highResAvatar_url = song.user.avatar_url.Replace("large.jpg", "t500x500.jpg"); for (int attempts = 0; attempts < 5; attempts++) { try { using (WebClient web = new WebClient()) { web.DownloadFile(highResAvatar_url, avatarFilepath); } TagLib.Picture artwork = new TagLib.Picture(avatarFilepath); artwork.Type = TagLib.PictureType.FrontCover; tagFile.Tag.Pictures = new[] { artwork }; break; } catch (Exception e) { Debug.WriteLine(e); } System.Threading.Thread.Sleep(50); // Pause 50ms before new attempt } if (avatarFilepath != null && File.Exists(avatarFilepath)) { File.Delete(avatarFilepath); } }
private static void SetTags(string filePath, string title, string album, string artist, uint year, string coverPath) { var fi = new FileInfo(filePath); if (fi.Length == 0) { return; } using (var tag = TagLib.File.Create(filePath)) { tag.Tag.Title = title; tag.Tag.Album = album; tag.Tag.Artists = new string[] { artist }; tag.Tag.Year = year; tag.Tag.Track = 1; //tag.Tag.TrackCount = 12; if (File.Exists(coverPath)) { var pictures = new TagLib.Picture[1]; pictures[0] = new TagLib.Picture(coverPath); tag.Tag.Pictures = pictures; } tag.Save(); } }
/// <summary> /// Get the album cover as Taglib instance. /// </summary> /// <returns>The album cover as Taglib instance.</returns> public TagLib.Id3v2.AttachedPictureFrame getAlbumImage() { TagLib.Picture picture = new TagLib.Picture(new TagLib.ByteVector(_imageBytes.ToArray())); TagLib.Id3v2.AttachedPictureFrame albumCoverPictFrame = new TagLib.Id3v2.AttachedPictureFrame(picture); albumCoverPictFrame.Type = TagLib.PictureType.FrontCover; albumCoverPictFrame.TextEncoding = TagLib.StringType.Latin1; return(albumCoverPictFrame); }
/// <summary> /// Downloads an album. /// </summary> /// <param name="album">The album to download.</param> /// <param name="downloadsFolder">The downloads folder.</param> /// <param name="tagTracks">True to tag tracks; false otherwise.</param> /// <param name="saveCoverArtInTags">True to save cover art in tags; false otherwise.</param> /// <param name="saveCovertArtInFolder">True to save cover art in the downloads folder; false otherwise.</param> /// <param name="convertCoverArtToJpg">True to convert the cover art to jpg; false otherwise.</param> /// <param name="resizeCoverArt">True to resize the covert art; false otherwise.</param> /// <param name="coverArtMaxSize">The maximum width/height of the cover art when resizing.</param> private void DownloadAlbum(Album album, String downloadsFolder, Boolean tagTracks, Boolean saveCoverArtInTags, Boolean saveCovertArtInFolder, Boolean convertCoverArtToJpg, Boolean resizeCoverArt, int coverArtMaxSize) { if (this.userCancelled) { // Abort return; } // Create directory to place track files String directoryPath = downloadsFolder + "\\" + album.Title.ToAllowedFileName() + "\\"; try { Directory.CreateDirectory(directoryPath); } catch { Log("An error occured when creating the album folder. Make sure you have the rights to write files in the folder you chose", LogType.Error); return; } TagLib.Picture artwork = null; // Download artwork if (saveCoverArtInTags || saveCovertArtInFolder) { artwork = DownloadCoverArt(album, downloadsFolder, saveCovertArtInFolder, convertCoverArtToJpg, resizeCoverArt, coverArtMaxSize); } // Download & tag tracks Task[] tasks = new Task[album.Tracks.Count]; Boolean[] tracksDownloaded = new Boolean[album.Tracks.Count]; for (int i = 0; i < album.Tracks.Count; i++) { // Temporarily save the index or we will have a race condition exception when i hits its maximum value int currentIndex = i; tasks[currentIndex] = Task.Factory.StartNew(() => tracksDownloaded[currentIndex] = DownloadAndTagTrack(directoryPath, album, album.Tracks[currentIndex], tagTracks, saveCoverArtInTags, artwork)); } // Wait for all tracks to be downloaded before saying the album is downloaded Task.WaitAll(tasks); if (!this.userCancelled) { // Tasks have not been aborted if (tracksDownloaded.All(x => x == true)) { Log("Successfully downloaded album \"" + album.Title + "\"", LogType.Success); } else { Log("Finished downloading album \"" + album.Title + "\". Some tracks could not be downloaded", LogType.Success); } } }
void saveFile(bool save = false) { if (saveAction || save) { using (TagLib.File file = TagLib.File.Create(currentFileName)) { try { file.Tag.Album = tagAlbumName.Text; file.Tag.Title = tagTitle.Text; string[] artists = tagArtist.Text.Split(';'); for (int i = 0; i < artists.Length; i++) { artists[i] = artists[i].Trim(); } file.Tag.Performers = artists; string[] al_artists = tagAlbumArtist.Text.Split(';'); for (int i = 0; i < al_artists.Length; i++) { al_artists[i] = al_artists[i].Trim(); } file.Tag.AlbumArtists = al_artists; if (i != null) { TagLib.Picture pic = new TagLib.Picture(); pic.Type = TagLib.PictureType.FrontCover; pic.MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg; pic.Description = "Cover"; using (MemoryStream ms = new MemoryStream()) { i.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); ms.Position = 0; pic.Data = TagLib.ByteVector.FromStream(ms); } file.Tag.Pictures = new TagLib.IPicture[1] { pic }; } file.Save(); AutoClosingMessageBox.show("Saved Successfully", "File Saved", 1000); loadFile(currentFileName); saved(); } catch (Exception ex) { //Temporarily write the file to AppData, for safety //string appDataPath = Path.Combine(Tools.getDataFolder(), Path.GetFileName(currentFileName)); //TagLib doesn't support that... //Give Up? MessageBox.Show("Error Occurred while saving file: " + ex.Message); } } } else { Hide(); //new OptionsForm().Show(); } }
internal void ExportOsuFile(OsuFile osu) { if (osu.Mode.HasFlag(osu.Mode) && osu.AudioFilename != null) { if (osu.AudioFilename.Extension == ".mp3") { FileInfo f = osu.AudioFilename.CopyTo(ConstructPath(osu.Title + osu.AudioFilename.Extension), true); TagLib.File file = TagLib.File.Create(f.FullName); file.Tag.Album = "Osu - " + osu.Creator; file.Tag.Comment = osu.Tags; file.Tag.Performers = new string[] { osu.Creator }; file.Tag.AlbumArtists = new string[] { (Utils.AsciiOnly?osu.Artist:osu.ArtistUnicode) }; file.Tag.Title = (Utils.AsciiOnly ? osu.Title : osu.TitleUnicode); file.Tag.Genres = new string[] { "Osu" }; using (MemoryStream ims = new MemoryStream()) { if (osu.Image != null) { Image img; try { img = Utils.ResizeImage(Image.FromFile(osu.Image.FullName), new Size(6000, 6000)); } catch { img = Image.FromFile(osu.Image.FullName); } TagLib.Picture pic = new TagLib.Picture(); pic.Type = TagLib.PictureType.FrontCover; pic.Description = osu.Image.Name; pic.MimeType = MediaTypeNames.Image.Jpeg; img.Save(ims, ImageFormat.Jpeg); ims.Position = 0; pic.Data = TagLib.ByteVector.FromStream(ims); file.Tag.Pictures = new TagLib.IPicture[] { pic }; } file.Save(); Console.WriteLine(file.Name); } } else { if (!Utils.OnlyMp3) { FileInfo f = osu.AudioFilename.CopyTo(ConstructPath(osu.AudioFilename.Name), true); } } } }
/// <summary> /// Downloads an album. /// </summary> /// <param name="album">The album to download.</param> private async Task DownloadAlbumAsync(Album album) { if (_cancelDownloads) { // Abort return; } // Create directory to place track files try { Directory.CreateDirectory(album.Path); } catch { LogAdded(this, new LogArgs("An error occured when creating the album folder. Make sure you have the rights to write files in the folder you chose", LogType.Error)); return; } TagLib.Picture artwork = null; // Download artwork if ((App.UserSettings.SaveCoverArtInTags || App.UserSettings.SaveCoverArtInFolder) && album.HasArtwork) { artwork = await DownloadCoverArtAsync(album); } // Download & tag tracks bool[] tracksDownloaded = new bool[album.Tracks.Count]; int[] indexes = Enumerable.Range(0, album.Tracks.Count).ToArray(); await Task.WhenAll(indexes.Select(async i => tracksDownloaded[i] = await DownloadAndTagTrackAsync(album, album.Tracks[i], artwork))); // Create playlist file if (App.UserSettings.CreatePlaylist && !_cancelDownloads) { new PlaylistCreator(album).SavePlaylistToFile(); LogAdded(this, new LogArgs($"Saved playlist for album \"{album.Title}\"", LogType.IntermediateSuccess)); } if (!_cancelDownloads) { // Tasks have not been aborted if (tracksDownloaded.All(x => x == true)) { LogAdded(this, new LogArgs($"Successfully downloaded album \"{album.Title}\"", LogType.Success)); } else { LogAdded(this, new LogArgs($"Finished downloading album \"{album.Title}\". Some tracks were not downloaded", LogType.Success)); } } }
private async void btnApplyInFolderImg_Click(object sender, RoutedEventArgs e) { var mySettings = new MetroDialogSettings() { NegativeButtonText = "Close now", AnimateShow = false, AnimateHide = false }; var controller = await this.ShowProgressAsync("Front Image Changing", "Preparing...", settings : mySettings); controller.SetIndeterminate(); controller.SetCancelable(true); controller.Maximum = Convert.ToDouble(m_FilesPath.Count); double dblCnt = 0.0; foreach (SoundSourceFilePathModel selected in listBox.SelectedItems) { string fPath = m_FilesPath.FirstOrDefault(p => System.IO.Path.GetFileName(p) == selected.FileName); string dir = System.IO.Path.GetDirectoryName(fPath); string coverImg = System.IO.Path.Combine(dir, "tag_front.jpg"); if (System.IO.File.Exists(coverImg)) { using (FileStream fstrm = new FileStream(coverImg, FileMode.Open)) { using (Stream coverStrm = fstrm) { TagLib.File tlFile = TagLib.File.Create(fPath); TagLib.Picture pic = new TagLib.Picture(); pic.Type = TagLib.PictureType.FrontCover; pic.Data = TagLib.ByteVector.FromStream(coverStrm); tlFile.Tag.Pictures = new TagLib.IPicture[] { pic }; tlFile.Save(); } } } controller.SetProgress(dblCnt); controller.SetMessage("Completed : " + System.IO.Path.GetFileName(fPath)); dblCnt += 1.0; await Task.Delay(50); } await controller.CloseAsync(); ListBoxBind(); SetFooterMsg("In Folder Image Apply Complete!!", "Total Sound Sources : " + int.Parse(dblCnt.ToString()).ToString()); }
private static void SetImage(string path, Image image) { TagLib.File file = TagLib.File.Create(path); TagLib.Picture pic = new TagLib.Picture(); pic.Type = TagLib.PictureType.FrontCover; pic.Description = "Cover"; pic.MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg; MemoryStream ms = new MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); ms.Position = 0; pic.Data = TagLib.ByteVector.FromStream(ms); file.Tag.Pictures = new TagLib.IPicture[] { pic }; file.Save(); ms.Close(); }
public void setAlbumArt(string imagePath) { TagLib.Picture picture = new TagLib.Picture(); picture.Type = TagLib.PictureType.FrontCover; picture.Description = "Cover"; picture.MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg; try { picture.Data = TagLib.ByteVector.FromPath(imagePath); } catch (Exception) { return; } this.filetag.Tag.Pictures = new TagLib.IPicture[] { picture }; }
/// <summary> /// 生成标签 /// </summary> /// <param name="tags">MP3标签</param> /// <param name="mp3FileDir">MP3文件夹</param> /// <param name="mp3Info">MP3信息</param> /// <param name="mediaItem">MP3所在专辑信息</param> private static void SetTags(TagLib.Tag tag, string mp3FileDir, Mp3Info mp3Info, MediaItem mediaItem) { tag.Title = mp3Info.Title; tag.Album = mediaItem.Title; var artists = mp3Info.GuessArtists(mediaItem.Title, out string companyName); if (artists != null && artists.Length > 0) { tag.AlbumArtists = new string[1] { artists[0] }; tag.Artists = artists; } // 唱片公司写到Grouping属性中? if (string.IsNullOrEmpty(companyName)) { tag.Grouping = companyName; } var trackIndex = mediaItem.Mp3Items?.FindIndex(x => x.Title == mp3Info.Title); if (trackIndex > -1) { tag.Track = (uint)trackIndex + 1; tag.TrackCount = (uint)mediaItem.Mp3Items.Count; } // 播放器不支持内嵌歌词, 目前还是放到备注里了 //tag.Lyrics = mp3Info.Lyric; tag.Comment = mp3Info.Lyric; //tag.Comment = "强森强森整理"; tag.Copyright = "北京典籍与经典老唱片数字化出版项目"; // 封面图片(默认名称为_avatar.jpg) var mp3CoverFilePath = Path.Combine(mp3FileDir, StaticVariables.ALBUM_MP3_COVER_NAME); if (System.IO.File.Exists(mp3CoverFilePath)) { var fileBytes = System.IO.File.ReadAllBytes(mp3CoverFilePath); var corverPic = new TagLib.Picture(new TagLib.ByteVector(fileBytes)); // apply corver tag.Pictures = new TagLib.IPicture[] { corverPic }; } }
/// <summary> /// Build the Pictures image from the content of the file /// </summary> /// <param name="path">path to the file</param> /// <param name="coverOnly">Try to load only a cover, not the system icon</param> /// <returns>Pictures image</returns> public void BuildCover(bool coverOnly) { TagLib.IPicture[] ret = null; if (TagLibFile != null) { string path = TagLibFile.Name; if (TagLibFile.Tag != null) { if (Type == MediaType.Image) { ret = new TagLib.Picture[] { new TagLib.Picture(path) }; } else if (TagLibFile.Tag.Pictures != null && TagLibFile.Tag.Pictures.Length > 0) { // Retain only the pictures, no the attachments of other types int count = 0; var pics = new List <TagLib.IPicture>(TagLibFile.Tag.Pictures.Length); foreach (TagLib.IPicture pic in TagLibFile.Tag.Pictures) { if (pic.Type != TagLib.PictureType.NotAPicture) { count++; pics.Add(pic); } } if (count > 0) { ret = count == TagLibFile.Tag.Pictures.Length ? TagLibFile.Tag.Pictures : pics.ToArray(); } } } if (ret is null && !coverOnly) { BuildCover(path); return; } } Pictures = ret; }
//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) { String fran = "F:/Reproductor de Musica/Reproductor de Musica/Resources/descarga (4).jpg";//"D:/Users/Gabo/Escritorio/Proyectos/Projects/Reproductor de Musica/Reproductor de Musica/Resources/descarga (4).jpg TagLib.Picture pic = new TagLib.Picture(fran); icon = pic; } else { icon = mp3.Tag.Pictures[0]; } return(icon); }
private bool addcoverart(string audiopath,string picturepath) { try { TagLib.File TagLibFile = TagLib.File.Create(audiopath); TagLib.Picture picture = new TagLib.Picture(picturepath); 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 TagLib.IPicture[1]; pictFrames[0] = (TagLib.IPicture)albumCoverPictFrame; TagLibFile.Tag.Pictures = pictFrames; TagLibFile.Save(); } catch { return false; } return true; }
private bool addcoverart(string audiopath, string picturepath) { try { TagLib.File TagLibFile = TagLib.File.Create(audiopath); TagLib.Picture picture = new TagLib.Picture(picturepath); 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 TagLib.IPicture[1]; pictFrames[0] = (TagLib.IPicture)albumCoverPictFrame; TagLibFile.Tag.Pictures = pictFrames; TagLibFile.Save(); } catch { return(false); } return(true); }
/// <inheritdoc /> public void AddMeta(string path, string title, string album, string author, int trackNo, int trackCount, string thumbnailPath) { var file = TagLib.File.Create(path); file.Tag.Title = title; file.Tag.Album = album; file.Tag.Performers = new[] { author }; file.Tag.Track = (uint)trackNo; file.Tag.TrackCount = (uint)trackCount; if (!string.IsNullOrWhiteSpace(thumbnailPath)) { var image = new TagLib.Picture(thumbnailPath); file.Tag.Pictures = new TagLib.IPicture[1] { image }; } file.Save(); }
/// <summary> /// タグ書込み /// </summary> /// <param name="row"></param> private void SaveTag(Row row) { string path = StringUtil.NullToBlank(row[(int)ColIndex.FullPath]); string extension = StringUtil.NullToBlank(row[(int)ColIndex.Extension]); string title = StringUtil.NullToBlank(row[(int)ColIndex.Title]); uint year = 0; DateTime releaseDate = DateTime.Parse("1900/1/1"); string date = StringUtil.NullToBlank(row[(int)ColIndex.ReleaseDate]); if (DateTime.TryParse(date, out releaseDate)) { year = (uint)releaseDate.Year; } if (extension.ToLower() == ".mp4") { //MP4のみ記入 var tagFile = TagLib.File.Create(path); tagFile.Tag.Title = title; tagFile.Tag.Year = year; tagFile.Tag.Performers = new string[] { StringUtil.NullToBlank(row[(int)ColIndex.Artist]) }; tagFile.Tag.Genres = new string[] { StringUtil.NullToBlank(row[(int)ColIndex.Genres]) }; tagFile.Tag.Comment = StringUtil.NullToBlank(row[(int)ColIndex.Comment]); //画像 Image img = this.TargetGrid.GetCellImage(row.Index, (int)ColIndex.Image); var ic = new System.Drawing.ImageConverter(); var ba = (byte[])ic.ConvertTo(img, typeof(byte[])); var byteVector = new TagLib.ByteVector(ba); var pic = new TagLib.Picture(byteVector); pic.Type = TagLib.PictureType.FrontCover; pic.Description = "Cover"; pic.MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg; tagFile.Tag.Pictures = new TagLib.IPicture[] { pic }; tagFile.Save(); } //リネーム var f = new FileInfo(path); f.MoveTo(f.DirectoryName + @"\" + StringUtil.ReplaceWindowsFileNGWord2Wide(title) + extension.ToLower()); }
public async Task <SongData> GetAlbumArt(int songId) { var filename = _dbContext.Songs.FirstOrDefault(song => song.Id == songId)?.Filename; if (filename == null) { return(null); } var file = TagLib.File.Create(filename); if (file.Tag.Pictures.Length < 1) { var albumSongLink = _dbContext.AlbumSongLinks.Include(_ => _.Album).FirstOrDefault(_ => _.SongId == songId); if (albumSongLink == null) { return(null); } var(dbArtData, dbArtMimeType) = await _vgmdbLookupHandler.GetAlbumArt(albumSongLink.Album.VgmdbLink); if (dbArtData == null || dbArtMimeType == null) { return(null); } var picture = new TagLib.Picture(new TagLib.ByteVector(dbArtData)); var pictureFrame = new TagLib.Id3v2.AttachedPictureFrame(picture) { Type = TagLib.PictureType.FrontCover }; TagLib.IPicture[] frames = { pictureFrame }; file.Tag.Pictures = frames; file.Save(); } var art = file.Tag.Pictures[0]; var songData = new SongData(art.MimeType, art.Data.Data); return(songData); }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnAdd_Click(object sender, EventArgs e) { ListViewItem item = new ListViewItem(txtDesc.Text); item.SubItems.Add(cmbPicType.Text); item.SubItems.Add(txtPath.Text); string include = ckInclude.Checked ? "Yes" : "No"; item.SubItems.Add(include); byte[] data = File.ReadAllBytes(txtPath.Text); // create picture TagLib.Picture p = new TagLib.Picture(); p.Data = data; p.Description = txtDesc.Text; p.MimeType = "image/" + Path.GetExtension(txtPath.Text); item.Tag = p; pictureList.Items.Add(item); this.pictures_dirty = true; ckInclude.Enabled = false; ckRelative.Enabled = false; }
public static TagLib.Picture ConvertToPicture(this Bitmap bitmap) { if (bitmap != null) { MemoryStream memoryStream = new MemoryStream(); bitmap.Save(memoryStream, ImageFormat.Png); memoryStream.Position = 0; TagLib.ByteVector vs = TagLib.ByteVector.FromStream(memoryStream); TagLib.Picture newpic = new TagLib.Picture(vs); vs.Clear(); memoryStream.Close(); return(newpic); } return(null); }
public override void Process() { base.Process(); try { var item = Info.Entity as SongViewModel; if (item == null) throw new Exception("item is null"); var folder = Path.Combine(Global.AppSettings["DownloadFolder"], item.Dir); if (folder != null && !Directory.Exists(folder)) Directory.CreateDirectory(folder); var mp3 = Path.Combine(folder, item.FileNameBase + ".mp3"); File.Copy(Info.FileName, mp3, true); if (item.Song.WriteId3) { var id3 = TagLib.File.Create(mp3); id3.Tag.Clear(); id3.Tag.Album = item.AlbumName; id3.Tag.Performers = new string[] { item.ArtistName }; id3.Tag.AlbumArtists = new string[] { item.ArtistName }; id3.Tag.Title = item.Name; id3.Tag.Comment = item.Id; if (item.TrackNo > 0) id3.Tag.Track = (uint)item.TrackNo; if (item.ImageSource != null) { var pic = new TagLib.Picture(item.ImageSource); id3.Tag.Pictures = new TagLib.IPicture[] { pic }; } id3.Save(); } item.HasMp3 = true; } catch (Exception e) { NotifyError(e); } }
TagLib.Picture[] CopyImages(string beatmapPath, TagLib.Picture existing) { //code modified from https://github.com/RaidMax/osu-replace //thanks for the regex i am smol brain string[] beatmapFiles = Directory.GetFiles(beatmapPath, "*.osu"); string regexString = "0,0,\".+\\..+\".*"; List <string> paths = new List <string>(); List <TagLib.Picture> pics = new List <TagLib.Picture>(); if (existing != null) { pics.Add(existing); } foreach (string beatmap in beatmapFiles) { string[] beatmapFile = File.ReadAllLines(beatmap); foreach (string line in beatmapFile) { var match = Regex.Match(line, regexString); if (match.Success) { string imagePath = Regex.Match(match.Value, "\".+\\..+\"").Value; imagePath = $"{beatmapPath}{Path.DirectorySeparatorChar}{imagePath.Substring(1, imagePath.Length - 2)}"; paths.Add(imagePath); } } } foreach (string s in paths) { pics.Add(new TagLib.Picture(s)); } return(pics.ToArray()); }
/// <summary> /// Downloads the cover art. /// </summary> /// <param name="album">The album to download.</param> /// <param name="downloadsFolder">The downloads folder.</param> /// <param name="saveCovertArtInFolder">True to save cover art in the downloads folder; false otherwise.</param> /// <param name="convertCoverArtToJpg">True to convert the cover art to jpg; false otherwise.</param> /// <param name="resizeCoverArt">True to resize the covert art; false otherwise.</param> /// <param name="coverArtMaxSize">The maximum width/height of the cover art when resizing.</param> /// <returns></returns> private TagLib.Picture DownloadCoverArt(Album album, String downloadsFolder, Boolean saveCovertArtInFolder, Boolean convertCoverArtToJpg, Boolean resizeCoverArt, int coverArtMaxSize) { // Compute path where to save artwork String artworkPath = (saveCovertArtInFolder ? downloadsFolder + "\\" + album.Title.ToAllowedFileName() : Path.GetTempPath()) + "\\" + album.Title.ToAllowedFileName() + Path.GetExtension(album.ArtworkUrl); TagLib.Picture artwork = null; int tries = 0; Boolean artworkDownloaded = false; do { var doneEvent = new AutoResetEvent(false); using (var webClient = new WebClient()) { // Update progress bar when downloading webClient.DownloadProgressChanged += (s, e) => { UpdateProgress(album.ArtworkUrl, e.BytesReceived); }; // Warn when downloaded webClient.DownloadFileCompleted += (s, e) => { if (!e.Cancelled && e.Error == null) { artworkDownloaded = true; // Convert/resize artwork if (convertCoverArtToJpg || resizeCoverArt) { var settings = new ResizeSettings(); if (convertCoverArtToJpg) { settings.Format = "jpg"; settings.Quality = 90; } if (resizeCoverArt) { settings.MaxHeight = coverArtMaxSize; settings.MaxWidth = coverArtMaxSize; } ImageBuilder.Current.Build(artworkPath, artworkPath, settings); } artwork = new TagLib.Picture(artworkPath) { Description = "Picture" }; // Delete the cover art file if it was saved in Temp if (!saveCovertArtInFolder) { try { System.IO.File.Delete(artworkPath); } catch { // Could not delete the file. Nevermind, it's in Temp/ folder... } } Log("Downloaded artwork for album \"" + album.Title + "\"", LogType.IntermediateSuccess); } else if (!e.Cancelled && e.Error != null) { if (tries < Constants.DownloadMaxTries) { Log("Unable to download artwork for album \"" + album.Title + "\". " + "Try " + tries + " of " + Constants.DownloadMaxTries, LogType.Warning); } else { Log("Unable to download artwork for album \"" + album.Title + "\". " + "Hit max retries of " + Constants.DownloadMaxTries, LogType.Error); } } // Else the download has been cancelled (by the user) doneEvent.Set(); }; lock (this.pendingDownloads) { if (this.userCancelled) { // Abort return(null); } // Register current download this.pendingDownloads.Add(webClient); // Start download webClient.DownloadFileAsync(new Uri(album.ArtworkUrl), artworkPath); } // Wait for download to be finished doneEvent.WaitOne(); lock (this.pendingDownloads) { this.pendingDownloads.Remove(webClient); } } } while (!artworkDownloaded && tries < Constants.DownloadMaxTries); return(artwork); }
/// <summary> /// Downloads and tags a track. Returns true if the track has been correctly downloaded; false otherwise. /// </summary> /// <param name="albumDirectoryPath">The path where to save the tracks.</param> /// <param name="album">The album of the track to download.</param> /// <param name="track">The track to download.</param> /// <param name="tagTrack">True to tag the track; false otherwise.</param> /// <param name="saveCoverArtInTags">True to save the cover art in the tag tracks; false otherwise.</param> /// <param name="artwork">The cover art.</param> private Boolean DownloadAndTagTrack(String albumDirectoryPath, Album album, Track track, Boolean tagTrack, Boolean saveCoverArtInTags, TagLib.Picture artwork) { Log("Downloading track \"" + track.Title + "\" from url: " + track.Mp3Url, LogType.VerboseInfo); // Set location to save the file String trackPath = albumDirectoryPath + track.GetFileName(album.Artist); int tries = 0; Boolean trackDownloaded = false; do { var doneEvent = new AutoResetEvent(false); using (var webClient = new WebClient()) { // Update progress bar when downloading webClient.DownloadProgressChanged += (s, e) => { UpdateProgress(track.Mp3Url, e.BytesReceived); }; // Warn & tag when downloaded webClient.DownloadFileCompleted += (s, e) => { tries++; if (!e.Cancelled && e.Error == null) { trackDownloaded = true; if (tagTrack) { // Tag (ID3) the file when downloaded TagLib.File tagFile = TagLib.File.Create(trackPath); tagFile.Tag.Album = album.Title; tagFile.Tag.AlbumArtists = new String[1] { album.Artist }; tagFile.Tag.Performers = new String[1] { album.Artist }; tagFile.Tag.Title = track.Title; tagFile.Tag.Track = (uint)track.Number; tagFile.Tag.Year = (uint)album.ReleaseDate.Year; tagFile.Save(); } if (saveCoverArtInTags && artwork != null) { // Save cover in tags when downloaded TagLib.File tagFile = TagLib.File.Create(trackPath); tagFile.Tag.Pictures = new TagLib.IPicture[1] { artwork }; tagFile.Save(); } Log("Downloaded track \"" + track.GetFileName(album.Artist) + "\" from album \"" + album.Title + "\"", LogType.IntermediateSuccess); } else if (!e.Cancelled && e.Error != null) { if (tries < Constants.DownloadMaxTries) { Log("Unable to download track \"" + track.GetFileName(album.Artist) + "\" from album \"" + album.Title + "\". " + "Try " + tries + " of " + Constants.DownloadMaxTries, LogType.Warning); } else { Log("Unable to download track \"" + track.GetFileName(album.Artist) + "\" from album \"" + album.Title + "\". " + "Hit max retries of " + Constants.DownloadMaxTries, LogType.Error); } } // Else the download has been cancelled (by the user) doneEvent.Set(); }; lock (this.pendingDownloads) { if (this.userCancelled) { // Abort return(false); } // Register current download this.pendingDownloads.Add(webClient); // Start download webClient.DownloadFileAsync(new Uri(track.Mp3Url), trackPath); } // Wait for download to be finished doneEvent.WaitOne(); lock (this.pendingDownloads) { this.pendingDownloads.Remove(webClient); } } } while (!trackDownloaded && tries < Constants.DownloadMaxTries); return(trackDownloaded); }
/// <summary> /// Downloads and returns the cover art of the specified album. Depending on UserSettings, save the cover art in /// the album folder. /// </summary> /// <param name="album">The album.</param> private async Task <TagLib.Picture> DownloadCoverArtAsync(Album album) { TagLib.Picture artworkInTags = null; int tries = 0; bool artworkDownloaded = false; TrackFile currentFile = DownloadingFiles.Where(f => f.Url == album.ArtworkUrl).First(); do { if (_cancelDownloads) { // Abort return(null); } using (var webClient = new WebClient()) { ProxyHelper.SetProxy(webClient); // Update progress bar when downloading webClient.DownloadProgressChanged += (s, e) => { currentFile.BytesReceived = e.BytesReceived; }; // Register current download _cancellationTokenSource.Token.Register(webClient.CancelAsync); // Start download try { await webClient.DownloadFileTaskAsync(album.ArtworkUrl, album.ArtworkTempPath); artworkDownloaded = true; } catch (WebException ex) when(ex.Status == WebExceptionStatus.RequestCanceled) { // Downloads cancelled by the user return(null); } catch (TaskCanceledException) { // Downloads cancelled by the user return(null); } catch (WebException) { // Connection closed probably because no response from Bandcamp if (tries < App.UserSettings.DownloadMaxTries) { LogAdded(this, new LogArgs($"Unable to download artwork for album \"{album.Title}\". Try {tries + 1} of {App.UserSettings.DownloadMaxTries}", LogType.Warning)); } else { LogAdded(this, new LogArgs($"Unable to download artwork for album \"{album.Title}\". Hit max retries of {App.UserSettings.DownloadMaxTries}", LogType.Error)); } } if (artworkDownloaded) { // Convert/resize artwork to be saved in album folder if (App.UserSettings.SaveCoverArtInFolder && (App.UserSettings.CoverArtInFolderConvertToJpg || App.UserSettings.CoverArtInFolderResize)) { var settings = new ResizeSettings(); if (App.UserSettings.CoverArtInFolderConvertToJpg) { settings.Format = "jpg"; settings.Quality = 90; } if (App.UserSettings.CoverArtInFolderResize) { settings.MaxHeight = App.UserSettings.CoverArtInFolderMaxSize; settings.MaxWidth = App.UserSettings.CoverArtInFolderMaxSize; } await Task.Run(() => { ImageBuilder.Current.Build(album.ArtworkTempPath, album.ArtworkPath, settings); // Save it to the album folder }); } else if (App.UserSettings.SaveCoverArtInFolder) { await FileHelper.CopyFileAsync(album.ArtworkTempPath, album.ArtworkPath); } // Convert/resize artwork to be saved in tags if (App.UserSettings.SaveCoverArtInTags && (App.UserSettings.CoverArtInTagsConvertToJpg || App.UserSettings.CoverArtInTagsResize)) { var settings = new ResizeSettings(); if (App.UserSettings.CoverArtInTagsConvertToJpg) { settings.Format = "jpg"; settings.Quality = 90; } if (App.UserSettings.CoverArtInTagsResize) { settings.MaxHeight = App.UserSettings.CoverArtInTagsMaxSize; settings.MaxWidth = App.UserSettings.CoverArtInTagsMaxSize; } await Task.Run(() => { ImageBuilder.Current.Build(album.ArtworkTempPath, album.ArtworkTempPath, settings); // Save it to %Temp% }); } artworkInTags = new TagLib.Picture(album.ArtworkTempPath) { Description = "Picture" }; try { File.Delete(album.ArtworkTempPath); } catch { // Could not delete the file. Nevermind, it's in %Temp% folder... } // Note the file as downloaded currentFile.Downloaded = true; LogAdded(this, new LogArgs($"Downloaded artwork for album \"{album.Title}\"", LogType.IntermediateSuccess)); } tries++; if (!artworkDownloaded && tries < App.UserSettings.DownloadMaxTries) { await WaitForCooldownAsync(tries); } } } while (!artworkDownloaded && tries < App.UserSettings.DownloadMaxTries); return(artworkInTags); }
/// <summary> /// Downloads and tags a track. Returns true if the track has been correctly downloaded; false otherwise. /// </summary> /// <param name="album">The album of the track to download.</param> /// <param name="track">The track to download.</param> /// <param name="artwork">The cover art.</param> private async Task <bool> DownloadAndTagTrackAsync(Album album, Track track, TagLib.Picture artwork) { LogAdded(this, new LogArgs($"Downloading track \"{track.Title}\" from url: {track.Mp3Url}", LogType.VerboseInfo)); int tries = 0; bool trackDownloaded = false; TrackFile currentFile = DownloadingFiles.Where(f => f.Url == track.Mp3Url).First(); if (File.Exists(track.Path)) { long length = new FileInfo(track.Path).Length; if (currentFile.Size > length - (currentFile.Size * App.UserSettings.AllowedFileSizeDifference) && currentFile.Size < length + (currentFile.Size * App.UserSettings.AllowedFileSizeDifference)) { LogAdded(this, new LogArgs($"Track already exists within allowed file size range: track \"{Path.GetFileName(track.Path)}\" from album \"{album.Title}\" - Skipping download!", LogType.IntermediateSuccess)); return(false); } } do { if (_cancelDownloads) { // Abort return(false); } using (var webClient = new WebClient()) { ProxyHelper.SetProxy(webClient); // Update progress bar when downloading webClient.DownloadProgressChanged += (s, e) => { currentFile.BytesReceived = e.BytesReceived; }; // Register current download _cancellationTokenSource.Token.Register(webClient.CancelAsync); // Start download try { await webClient.DownloadFileTaskAsync(track.Mp3Url, track.Path); trackDownloaded = true; LogAdded(this, new LogArgs($"Downloaded track \"{track.Title}\" from url: {track.Mp3Url}", LogType.VerboseInfo)); } catch (WebException ex) when(ex.Status == WebExceptionStatus.RequestCanceled) { // Downloads cancelled by the user return(false); } catch (TaskCanceledException) { // Downloads cancelled by the user return(false); } catch (WebException) { // Connection closed probably because no response from Bandcamp if (tries + 1 < App.UserSettings.DownloadMaxTries) { LogAdded(this, new LogArgs($"Unable to download track \"{Path.GetFileName(track.Path)}\" from album \"{album.Title}\". Try {tries + 1} of {App.UserSettings.DownloadMaxTries}", LogType.Warning)); } else { LogAdded(this, new LogArgs($"Unable to download track \"{Path.GetFileName(track.Path)}\" from album \"{album.Title}\". Hit max retries of {App.UserSettings.DownloadMaxTries}", LogType.Error)); } } if (trackDownloaded) { if (App.UserSettings.ModifyTags) { // Tag (ID3) the file when downloaded var tagFile = TagLib.File.Create(track.Path); tagFile = TagHelper.UpdateArtist(tagFile, album.Artist, App.UserSettings.TagArtist); tagFile = TagHelper.UpdateAlbumArtist(tagFile, album.Artist, App.UserSettings.TagAlbumArtist); tagFile = TagHelper.UpdateAlbumTitle(tagFile, album.Title, App.UserSettings.TagAlbumTitle); tagFile = TagHelper.UpdateAlbumYear(tagFile, (uint)album.ReleaseDate.Year, App.UserSettings.TagYear); tagFile = TagHelper.UpdateTrackNumber(tagFile, (uint)track.Number, App.UserSettings.TagTrackNumber); tagFile = TagHelper.UpdateTrackTitle(tagFile, track.Title, App.UserSettings.TagTrackTitle); tagFile = TagHelper.UpdateTrackLyrics(tagFile, track.Lyrics, App.UserSettings.TagLyrics); tagFile = TagHelper.UpdateComments(tagFile, App.UserSettings.TagComments); tagFile.Save(); LogAdded(this, new LogArgs($"Tags saved for track \"{Path.GetFileName(track.Path)}\" from album \"{album.Title}\"", LogType.VerboseInfo)); } if (App.UserSettings.SaveCoverArtInTags && artwork != null) { // Save cover in tags when downloaded var tagFile = TagLib.File.Create(track.Path); tagFile.Tag.Pictures = new TagLib.IPicture[1] { artwork }; tagFile.Save(); LogAdded(this, new LogArgs($"Cover art saved in tags for track \"{Path.GetFileName(track.Path)}\" from album \"{album.Title}\"", LogType.VerboseInfo)); } // Note the file as downloaded currentFile.Downloaded = true; LogAdded(this, new LogArgs($"Downloaded track \"{Path.GetFileName(track.Path)}\" from album \"{album.Title}\"", LogType.IntermediateSuccess)); } tries++; if (!trackDownloaded && tries < App.UserSettings.DownloadMaxTries) { await WaitForCooldownAsync(tries); } } } while (!trackDownloaded && tries < App.UserSettings.DownloadMaxTries); return(trackDownloaded); }
public void LoadAlbumArt(TagLib.File fileInfo) { if ((_config.extractAlbumArt || _config.CopyAlbumArt) && fileInfo != null) foreach (TagLib.IPicture picture in fileInfo.Tag.Pictures) if (picture.Type == TagLib.PictureType.FrontCover) if (picture.MimeType == "image/jpeg") { _albumArt.Add(picture); return; } if ((_config.extractAlbumArt || _config.embedAlbumArt) && !_isCD) { foreach (string tpl in _config.advanced.CoverArtFiles) { string name = tpl.Replace("%album%", Metadata.Title).Replace("%artist%", Metadata.Artist); string imgPath = Path.Combine(_isArchive ? _archiveCUEpath : _inputDir, name); bool exists = _isArchive ? _archiveContents.Contains(imgPath) : File.Exists(imgPath); if (exists) { TagLib.File.IFileAbstraction file = _isArchive ? (TagLib.File.IFileAbstraction)new ArchiveFileAbstraction(this, imgPath) : (TagLib.File.IFileAbstraction)new TagLib.File.LocalFileAbstraction(imgPath); TagLib.Picture pic = new TagLib.Picture(file); pic.Description = name; _albumArt.Add(pic); return; } } if (!_isArchive && _config.advanced.CoverArtSearchSubdirs) { List<string> allfiles = new List<string>(Directory.GetFiles(_inputDir, "*.jpg", SearchOption.AllDirectories)); // TODO: archive case foreach (string tpl in _config.advanced.CoverArtFiles) { string name = tpl.Replace("%album%", Metadata.Title).Replace("%artist%", Metadata.Artist); List<string> matching = allfiles.FindAll(s => Path.GetFileName(s) == name); if (matching.Count == 1) { string imgPath = matching[0]; TagLib.File.IFileAbstraction file = _isArchive ? (TagLib.File.IFileAbstraction)new ArchiveFileAbstraction(this, imgPath) : (TagLib.File.IFileAbstraction)new TagLib.File.LocalFileAbstraction(imgPath); TagLib.Picture pic = new TagLib.Picture(file); pic.Description = name; _albumArt.Add(pic); return; } } if (CUEToolsSelection != null && ((Action == CUEAction.Encode && allfiles.Count < 32) || (Action != CUEAction.Encode && allfiles.Count < 2) ) ) { foreach (string imgPath in allfiles) { TagLib.Picture pic = new TagLib.Picture(imgPath); if (imgPath.StartsWith(_inputDir)) pic.Description = imgPath.Substring(_inputDir.Length).Trim(Path.DirectorySeparatorChar); else pic.Description = Path.GetFileName(imgPath); _albumArt.Add(pic); } if (_albumArt.Count > 0) { CUEToolsSelectionEventArgs e = new CUEToolsSelectionEventArgs(); e.choices = _albumArt.ToArray(); CUEToolsSelection(this, e); TagLib.IPicture selected = e.selection == -1 ? null : _albumArt[e.selection]; _albumArt.RemoveAll(t => t != selected); } } } } }
/// <summary> /// Write tags/metadata to files (generic) /// </summary> /// <param name="outputFile">File to write into</param> private bool WriteGenericTags(string outputFile) { TagLib.File NewTagFile; try { TagLib.ByteVector.UseBrokenLatin1Behavior = true; // Use Default Encoding for Latin-1 strings instead of code page 1252 (this is how WMP works, technically broken and should ideally be code page 1252 or UTF-8, but WMP takes the default local encoding). Required for non english symbols NewTagFile = TagLib.File.Create(outputFile); switch (FilePaths.CleanExt(outputFile)) { case ".mkv": // Tag mapping taken from http://matroska.org/technical/specs/tagging/othertagsystems/comparetable.html // TODO: Very weak support for MKV tags provided by TagLib (only 4 parameters), need to enhance library to add more support _jobLog.WriteEntry(this, "Write Tags: MKV file detected using Matroska", Log.LogEntryType.Information); TagLib.Matroska.Tag MKVTag = NewTagFile.GetTag(TagLib.TagTypes.Id3v2) as TagLib.Matroska.Tag; MKVTag.Title = _videoTags.Title; MKVTag.Album = _videoTags.SubTitle; MKVTag.Comment = _videoTags.Description; MKVTag.Performers = _videoTags.Genres; break; case ".avi": // AVI Extended INFO Tags: http://abcavi.kibi.ru/infotags.htm _jobLog.WriteEntry(this, "Write Tags: AVI file detected using RiffTag", Log.LogEntryType.Information); TagLib.Riff.InfoTag RiffTag = NewTagFile.GetTag(TagLib.TagTypes.RiffInfo) as TagLib.Riff.InfoTag; RiffTag.Title = _videoTags.Title; RiffTag.SetValue("ISBJ", _videoTags.SubTitle); // Subject RiffTag.Comment = _videoTags.Description; RiffTag.Genres = _videoTags.Genres; RiffTag.Track = (uint)_videoTags.Episode; RiffTag.Year = (uint)_videoTags.Season; // Disc is always zero for RiffTag RiffTag.SetValue("ISFT", "MCEBuddy2x"); // Software if (!String.IsNullOrWhiteSpace(_videoTags.BannerFile)) { TagLib.Picture VideoPicture = new TagLib.Picture(_videoTags.BannerFile); RiffTag.Pictures = new TagLib.Picture[] { VideoPicture }; } break; case ".wmv": _jobLog.WriteEntry(this, "Write Tags: WMV file detected using AsfTag", Log.LogEntryType.Information); TagLib.Asf.Tag AsfTag = NewTagFile.GetTag(TagLib.TagTypes.Asf) as TagLib.Asf.Tag; AsfTag.Title = _videoTags.Title; AsfTag.Comment = _videoTags.Description; AsfTag.Genres = _videoTags.Genres; AsfTag.Disc = (uint)_videoTags.Season; AsfTag.Track = (uint)_videoTags.Episode; AsfTag.SetDescriptorString(_videoTags.SubTitle, "WM/SubTitle"); AsfTag.SetDescriptorString(_videoTags.Description, "WM/SubTitleDescription"); AsfTag.SetDescriptorString(_videoTags.Network, "WM/MediaStationName"); AsfTag.SetDescriptors("WM/MediaIsMovie", new TagLib.Asf.ContentDescriptor("WM/MediaIsMovie", _videoTags.IsMovie)); AsfTag.SetDescriptors("WM/MediaIsSport", new TagLib.Asf.ContentDescriptor("WM/MediaIsSport", _videoTags.IsSports)); AsfTag.SetDescriptors("WM/WMRVEncodeTime", new TagLib.Asf.ContentDescriptor("WM/WMRVEncodeTime", (ulong)_videoTags.RecordedDateTime.Ticks)); AsfTag.SetDescriptorString(_videoTags.Rating, "WM/ParentalRating"); if (_videoTags.OriginalBroadcastDateTime > GlobalDefs.NO_BROADCAST_TIME) { if (_videoTags.IsMovie) AsfTag.SetDescriptorString(_videoTags.OriginalBroadcastDateTime.Year.ToString(), "WM/OriginalReleaseTime"); else AsfTag.SetDescriptorString(_videoTags.OriginalBroadcastDateTime.ToString("s") + "Z", "WM/MediaOriginalBroadcastDateTime"); } if (!String.IsNullOrWhiteSpace(_videoTags.BannerFile)) { TagLib.Picture VideoPicture = new TagLib.Picture(_videoTags.BannerFile); AsfTag.Pictures = new TagLib.Picture[] { VideoPicture }; } break; case ".mp3": _jobLog.WriteEntry(this, "Write Tags: MP3 file detected using ID3v2", Log.LogEntryType.Information); TagLib.Id3v2.Tag MP3Tag = NewTagFile.GetTag(TagLib.TagTypes.Id3v2) as TagLib.Id3v2.Tag; if (!String.IsNullOrWhiteSpace(_videoTags.SubTitle)) MP3Tag.Title = _videoTags.SubTitle; else MP3Tag.Title = _videoTags.Title; MP3Tag.Album = _videoTags.Title; MP3Tag.Comment = _videoTags.Description; MP3Tag.Genres = _videoTags.Genres; MP3Tag.Disc = (uint)_videoTags.Season; MP3Tag.Track = (uint)_videoTags.Episode; if (!String.IsNullOrWhiteSpace(_videoTags.BannerFile)) { TagLib.Picture VideoPicture = new TagLib.Picture(_videoTags.BannerFile); MP3Tag.Pictures = new TagLib.Picture[] { VideoPicture }; } break; default: _jobLog.WriteEntry(this, "Write Tags: Unknown file detected -> " + FilePaths.CleanExt(outputFile) + ", writing generic tags", Log.LogEntryType.Warning); NewTagFile.Tag.Title = _videoTags.Title; // Generic Tags NewTagFile.Tag.Album = _videoTags.SubTitle; NewTagFile.Tag.Comment = _videoTags.Description; NewTagFile.Tag.Genres = _videoTags.Genres; NewTagFile.Tag.Genres = _videoTags.Genres; NewTagFile.Tag.Disc = (uint)_videoTags.Season; NewTagFile.Tag.Track = (uint)_videoTags.Episode; if (!String.IsNullOrWhiteSpace(_videoTags.BannerFile)) { TagLib.Picture VideoPicture = new TagLib.Picture(_videoTags.BannerFile); NewTagFile.Tag.Pictures = new TagLib.Picture[] { VideoPicture }; } break; } } catch (Exception Ex) { _jobLog.WriteEntry(this, Localise.GetPhrase("Unable to write meta data to file") + " " + outputFile + ". " + Ex.Message, Log.LogEntryType.Warning); return false; } try { _jobLog.WriteEntry(this, "About to write Tags", Log.LogEntryType.Debug); NewTagFile.Save(); } catch (Exception Ex) { _jobLog.WriteEntry(this, Localise.GetPhrase("Unable to write meta data to file") + " " + outputFile + ". " + Ex.Message, Log.LogEntryType.Warning); return false; } return true; }
private void ProcessFolder(string path) { Console.WriteLine(string.Format("Folder: {0}", path)); string[] files; try { files = Directory.GetFiles(path); }catch (Exception ex) { Console.WriteLine("Error accessing folder"); Console.WriteLine(ex.Message); return; } List<TagLib.File> tagFiles = new List<TagLib.File>(); foreach (string file in files) { m_TotalFiles++; try { TagLib.File f = TagLib.File.Create(file); if (f.Properties.MediaTypes == TagLib.MediaTypes.Audio) tagFiles.Add(f); } catch (Exception) { } } if (tagFiles.Count > 0) { string fArtist = null; string fAlbum = null; bool unique = true; foreach (TagLib.File f in tagFiles) { string artist = !string.IsNullOrEmpty(f.Tag.FirstAlbumArtist) ? f.Tag.FirstAlbumArtist : f.Tag.FirstPerformer; string album = f.Tag.Album; if (fArtist == null && fAlbum == null) { fArtist = artist; fAlbum = album; } else { if (fArtist != artist || fAlbum != album) { unique = false; } } if (!string.IsNullOrEmpty(artist) && !string.IsNullOrEmpty(album)) { if (f.Tag.Pictures.Length == 0 || m_Options.Overwrite) { artist = artist.Trim(); album = album.Trim(); Console.WriteLine(string.Format(" File : {0}", f.Name)); Console.WriteLine(string.Format(" Artist: {0}", artist)); Console.WriteLine(string.Format(" Album : {0}", album)); Console.Write(" Getting album art..."); string url = LastfmScrobbler.GetAlbumArt(artist, album, Scrobbler.ImageSize.mega); if (!string.IsNullOrEmpty(url)) { Console.WriteLine("found"); string imagePath = string.Empty; if (!m_ImagesCache.TryGetValue(url, out imagePath)) { Guid imageId = System.Guid.NewGuid(); imagePath = string.Format("{0}\\{1}", m_TempPath, imageId.ToString() + ".jpg"); if (SaveFile(url, imagePath)) m_ImagesCache[url] = imagePath; else imagePath = string.Empty; } if (!string.IsNullOrEmpty(imagePath)) { TagLib.Picture[] pictures = new TagLib.Picture[1]; TagLib.Picture picture = new TagLib.Picture(imagePath); pictures[0] = picture; f.Tag.Pictures = pictures; Console.Write(" Tagging file..."); try { f.Save(); Console.WriteLine("done"); m_TaggedFiles++; } catch (Exception ex) { Console.WriteLine("failed"); Console.WriteLine(" Error tagging file"); Console.WriteLine(ex.Message); } } } else { Console.WriteLine("not found"); } } } } if (unique && !string.IsNullOrEmpty(m_Options.FileName)) { string filename = string.Format("{0}\\{1}", path, m_Options.FileName); if (m_Options.Overwrite || !File.Exists(filename)){ Console.WriteLine(" Saving folder file..."); string url = LastfmScrobbler.GetAlbumArt(fArtist, fAlbum, Scrobbler.ImageSize.mega); if (!string.IsNullOrEmpty(url)) { string imagePath = string.Empty; if (!m_ImagesCache.TryGetValue(url, out imagePath)) { Guid imageId = System.Guid.NewGuid(); imagePath = string.Format("{0}\\{1}", m_TempPath, imageId.ToString() + ".jpg"); if (SaveFile(url, imagePath)) m_ImagesCache[url] = imagePath; else imagePath = string.Empty; } if (!string.IsNullOrEmpty(imagePath)) { try { File.Copy(imagePath, filename); }catch (Exception ex) { Console.WriteLine(" Error copying file"); Console.WriteLine(ex.Message); } } } } } } if (m_Options.Recursive) { string[] dirs = Directory.GetDirectories(path); foreach (string dir in dirs) { ProcessFolder(dir); } } }
public void SetArtwork( byte[] artworkData ) { if(File.Exists(FileName)) { try { var mediaFileStream = TagLib.File.Create( FileName ); if ( mediaFileStream.Tag.Pictures != null ) { TagLib.Picture pic = new TagLib.Picture( ); pic.Data = artworkData; // mediaFileStream.Tag.Pictures [ 0 ] = pic; TagLib.IPicture newArt = new TagLib.Picture( ); newArt.Data = artworkData; mediaFileStream.Tag.Pictures = new TagLib.IPicture [ 1 ] { newArt }; } else { mediaFileStream.Tag.Pictures = new TagLib.IPicture[1]; mediaFileStream.Tag.Pictures [ 0 ].Data = artworkData; } mediaFileStream.Save( ); } catch(Exception ex) { System.Windows.MessageBox.Show( ex.Message + System.Environment.NewLine + ex.StackTrace ); } } }
/// <summary> /// Downloads the cover art. /// </summary> /// <param name="album">The album to download.</param> /// <param name="downloadsFolder">The downloads folder.</param> /// <param name="saveCovertArtInFolder">True to save cover art in the downloads folder; false otherwise.</param> /// <param name="convertCoverArtToJpg">True to convert the cover art to jpg; false otherwise.</param> /// <param name="resizeCoverArt">True to resize the covert art; false otherwise.</param> /// <param name="coverArtMaxSize">The maximum width/height of the cover art when resizing.</param> /// <returns></returns> private TagLib.Picture DownloadCoverArt(Album album, String downloadsFolder, Boolean saveCovertArtInFolder, Boolean convertCoverArtToJpg, Boolean resizeCoverArt, int coverArtMaxSize) { // Compute path where to save artwork String artworkPath = ( saveCovertArtInFolder ? downloadsFolder + "\\" + album.Title.ToAllowedFileName() : Path.GetTempPath() ) + "\\" + album.Title.ToAllowedFileName() + Path.GetExtension(album.ArtworkUrl); TagLib.Picture artwork = null; int tries = 0; Boolean artworkDownloaded = false; do { var doneEvent = new AutoResetEvent(false); using (var webClient = new WebClient()) { // Update progress bar when downloading webClient.DownloadProgressChanged += (s, e) => { UpdateProgress(album.ArtworkUrl, e.BytesReceived); }; // Warn when downloaded webClient.DownloadFileCompleted += (s, e) => { if (!e.Cancelled && e.Error == null) { artworkDownloaded = true; // Convert/resize artwork if (convertCoverArtToJpg || resizeCoverArt) { var settings = new ResizeSettings(); if (convertCoverArtToJpg) { settings.Format = "jpg"; settings.Quality = 90; } if (resizeCoverArt) { settings.MaxHeight = coverArtMaxSize; settings.MaxWidth = coverArtMaxSize; } ImageBuilder.Current.Build(artworkPath, artworkPath, settings); } artwork = new TagLib.Picture(artworkPath) { Description = "Picture" }; // Delete the cover art file if it was saved in Temp if (!saveCovertArtInFolder) { try { System.IO.File.Delete(artworkPath); } catch { // Could not delete the file. Nevermind, it's in Temp/ folder... } } Log("Downloaded artwork for album \"" + album.Title + "\"", LogType.IntermediateSuccess); } else if (!e.Cancelled && e.Error != null) { if (tries < Constants.DownloadMaxTries) { Log("Unable to download artwork for album \"" + album.Title + "\". " + "Try " + tries + " of " + Constants.DownloadMaxTries, LogType.Warning); } else { Log("Unable to download artwork for album \"" + album.Title + "\". " + "Hit max retries of " + Constants.DownloadMaxTries, LogType.Error); } } // Else the download has been cancelled (by the user) doneEvent.Set(); }; lock (this.pendingDownloads) { if (this.userCancelled) { // Abort return null; } // Register current download this.pendingDownloads.Add(webClient); // Start download webClient.DownloadFileAsync(new Uri(album.ArtworkUrl), artworkPath); } // Wait for download to be finished doneEvent.WaitOne(); lock (this.pendingDownloads) { this.pendingDownloads.Remove(webClient); } } } while (!artworkDownloaded && tries < Constants.DownloadMaxTries); return artwork; }
private void UpdateTags() { try { TagLib.File file = TagLib.File.Create(filePath); if (coverImageBytes != null) { TagLib.Picture picture = new TagLib.Picture(new ByteArrayFileAbstraction("test", coverImageBytes)); TagLib.Id3v2.AttachedPictureFrame coverPictureFrame = new TagLib.Id3v2.AttachedPictureFrame(picture); coverPictureFrame.MimeType = MediaTypeNames.Image.Jpeg; coverPictureFrame.Type = TagLib.PictureType.FrontCover; file.Tag.Pictures = new TagLib.IPicture[] { coverPictureFrame }; } else { file.Tag.Pictures = new TagLib.IPicture[0]; } file.Tag.Performers = new string[] { Artist }; file.Tag.Title = Title; file.Tag.AlbumArtists = new string[] { AlbumArtist }; file.Tag.Album = Album; if (Genre != null) file.Tag.Genres = new string[] { Genre }; file.Tag.Year = uint.Parse(Year); file.Save(); file.Dispose(); } catch (Exception ex) { SendErrorMessage(ex.Message); } }
public void AddAlbumArt(byte[] encoded) { var data = new TagLib.ByteVector(encoded); var picture = new TagLib.Picture(data); picture.Type = TagLib.PictureType.FrontCover; _albumArt.Add(picture); }
public void Button_Click(object sender, RoutedEventArgs e) { using (Context db = new Context()) { using (TagLib.File FD = TagLib.File.Create(Path)) { int audioId = Id; var audio = db.Audios.Where(a => a.id == audioId).FirstOrDefault(); ///*audio.Title = */ FD.Tag.Title = TrackTitle; audio.Title = TrackTitle; FD.Tag.Performers = new string[] { Author }; audio.Singer = Author; FD.Tag.Album = Album; audio.Album = Album; //FD.Tag.Genres = new string[] { Ganre }; // FD.Tag.Year = Year; ///*audio.Singer = */FD.Tag.Performers[0] = Author; ///*audio.Album = */FD.Tag.Album = Album; FD.Tag.Genres = new string[] { Genre }; try { FD.Tag.Year = Convert.ToUInt32(Year); } catch { } var i = ImageBox.Source as BitmapImage; //(YourImage.Source as BitmapImage).UriSource try { if (ImagePath != "") { TagLib.Picture artwork = new TagLib.Picture(ImagePath); artwork.Type = TagLib.PictureType.FrontCover; FD.Tag.Pictures = new TagLib.IPicture[] { artwork }; } } catch { } //FD.Tag.Pictures[0] = PlaylistNameDialog.BufferFromImage(i); try { FD.Save(); FD.Dispose(); db.SaveChanges(); MessageBox.Show("saved"); this.Close(); } catch (Exception ex) { MessageBox.Show("Файл занят другим процессом\n" + ex.ToString()); } ////playlistList.Items.Add(playlist.Name); // audio. //db.Audios.Add(audio); } } }
/// <summary> /// Добавляет к файлу обложку /// </summary> /// <param name="mp3_path">Путь к MP3 файлу</param> /// <param name="cover_path">Путь к обложке</param> private void assignCover(string mp3_path, string cover_path) { try { // Формируем картинку в кадр Id3v2 TagLib.Picture pic = new TagLib.Picture(cover_path); TagLib.Id3v2.AttachedPictureFrame albumCoverPictFrame = new TagLib.Id3v2.AttachedPictureFrame(pic); albumCoverPictFrame.MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg; albumCoverPictFrame.Type = TagLib.PictureType.FrontCover; TagLib.IPicture[] ipic = { albumCoverPictFrame }; // Открываем файл TagLib.File file = TagLib.File.Create(mp3_path); file.Tag.Pictures = ipic; file.Save(); } catch (Exception e) { Error("Ошибка сохранения файла."); } }