/// <summary> /// Based on the Options set, use the correct version for ID3 /// Eventually remove V1 or V2 tags, if set in the options /// </summary> /// <param name = "File"></param> public static File FormatID3Tag(File file) { if (file.MimeType == "taglib/mp3") { var options = (ServiceLocator.Current.GetInstance(typeof(ISettingsManager)) as ISettingsManager)?.GetOptions; Tag id3v2_tag = file.GetTag(TagTypes.Id3v2) as Tag; if (id3v2_tag != null && options.MainSettings.ID3V2Version > 0) { id3v2_tag.Version = (byte)options.MainSettings.ID3V2Version; } // Remove V1 Tags, if checked or "Save V2 only checked" if (options.MainSettings.RemoveID3V1 || options.MainSettings.ID3Version == 2) { file.RemoveTags(TagTypes.Id3v1); } // Remove V2 Tags, if checked or "Save V1 only checked" if (options.MainSettings.RemoveID3V2 || options.MainSettings.ID3Version == 1) { file.RemoveTags(TagTypes.Id3v2); } // Remove V2 Tags, if Ape checked if (options.MainSettings.ID3V2Version == 0) { file.RemoveTags(TagTypes.Id3v2); } else { file.RemoveTags(TagTypes.Ape); } } return(file); }
private static void SetTagData(TagLib.File file, SongTagData tagData) { file.RemoveTags(TagTypes.Id3v1); file.RemoveTags(TagTypes.Id3v2); file.RemoveTags(TagTypes.Ape); // We set only Id3v2 tag. // Id3v1 stores genres as index from predefined genre list. // This list is pretty limited and doesn't contain frequently used tags like 'Symphonic Metal' or 'Nu metal'. // The list of available genres for Id3v2 tag could be obtained from TagLib.Genres.Audio. var tag = file.GetTag(TagTypes.Id3v2, true); FillTag(tag, tagData); file.Save(); }
public void RemoveAllTags(string path) { TagLib.File file = null; try { file = TagLib.File.Create(path); file.RemoveTags(TagLib.TagTypes.AllTags); file.Save(); } catch (CorruptFileException ex) { _logger.Warn(ex, $"Tag removal failed for {path}. File is corrupt"); } catch (Exception ex) { _logger.Warn() .Exception(ex) .Message($"Tag removal failed for {path}") .WriteSentryWarn("Tag removal failed") .Write(); } finally { file?.Dispose(); } }
public SongTag(string filePath) { if (!System.IO.File.Exists(filePath)) { return; } TagLib.Id3v2.Tag.DefaultVersion = 3; TagLib.Id3v2.Tag.ForceDefaultVersion = true; tagFile = TagLib.File.Create(filePath); tagFile.RemoveTags(tagFile.TagTypes & ~tagFile.TagTypesOnDisk); Title = tagFile.Tag.Title; Track = tagFile.Tag.Track.ToString(); Album = tagFile.Tag.Album; Artist = tagFile.Tag.FirstPerformer; Year = tagFile.Tag.Year.ToString(); Length = tagFile.Properties.Duration.ToString(@"h\:mm\:ss"); IPicture picture = tagFile.Tag.Pictures.Length == 0 ? null : tagFile.Tag.Pictures[0]; if (picture != null) { byte[] imageBytes = (byte[])picture.Data.Data; Art = Image.FromStream(new MemoryStream(imageBytes)); } }
/// <summary> /// Strip all tags from the file. /// This command writes to disk. /// </summary> /// <returns> /// An <see cref="OggTagWriteCommandReturn"/> indicating the result of the operation /// </returns> public OggTagWriteCommandReturn RemoveAllTags() { // Dead simple (in theory) m_TagLibFile.RemoveTags(TagTypes.AllTags); m_TagLibFile.Save(); // Done? return(OggTagWriteCommandReturn.Success); }
void RemoveTags(string file) { try { TagLib.File MetaFile = TagLib.File.Create(Txt_folderSelected.Text + "\\" + file); MetaFile.RemoveTags(TagTypes.AllTags); Rtb_output.AppendText("\n" + file + " : Tags have been removed"); } catch (Exception ex) { MessageBox.Show(ex.Message, "An Error has Occured", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void UpdateInfoFromFile(string fp) { try { using (TagLib.File f = TagLib.File.Create(Location)) { f.RemoveTags(f.TagTypes & ~f.TagTypesOnDisk); // read tags and their versions as is from file this.Size = (decimal)f.InvariantEndPosition; this.Tags = f.Tag; this.Properties = f.Properties; } } catch (Exception ex) { DebugHelper.WriteException(ex, "Error reading info from file"); } }
/// <summary> /// This refreshes the file to get rid of unused bytes and saves all made changes. /// </summary> /// <param name="Item"></param> /// <param name="Source"></param> public static void Refresh(this TagLib.File Item, string Source) { Item.Save(); Item.Dispose(); TagLib.File tagFile = TagLib.File.Create(Source); TagLib.Tag tempTag = new TagLib.Id3v2.Tag(); tagFile.Tag.CopyTo(tempTag, true); tagFile.RemoveTags(TagLib.TagTypes.AllTags); tagFile.Save(); tagFile.Dispose(); TagLib.File tagFile2 = TagLib.File.Create(Source); tempTag.CopyTo(tagFile2.Tag, true); tagFile2.Save(); tagFile2.Dispose(); }
public byte[] RemoveAllTags(byte[] data) { Stream dataStream = new MemoryStream(data); TagLib.File tagData = TagLib.File.Create(new FileBytesAbstraction("tempFile.mp3", dataStream)); //TagLib.Tag tempTags = new TagLib.Id3v2.Tag(); //tagData.Tag.Lyrics = "test lyric"; tagData.RemoveTags(TagLib.TagTypes.AllTags); //tagData.Tag.CopyTo(tempTags, true); tagData.Save(); tagData.Dispose(); //tagData = TagLib.File.Create(new FileBytesAbstraction(audioFile, dataStream)); //tempTags.CopyTo(tagData.Tag, true); //tagData.Save(); //tagData.Dispose(); byte[] dStream = new byte[dataStream.Length]; dataStream.Read(dStream, 0, dStream.Length); return(dStream); }
/// <summary> /// Save the Modified file /// </summary> /// <param name="track"></param> /// <param name="errorMessage"></param> /// <returns></returns> public static bool SaveFile(TrackData track, ref string errorMessage) { errorMessage = ""; if (!track.Changed) { return(true); } if (track.Readonly && !Options.MainSettings.ChangeReadOnlyAttributte && (Options.ReadOnlyFileHandling == 0 || Options.ReadOnlyFileHandling == 2)) { Form dlg = new ReadOnlyDialog(track.FullFileName); DialogResult dlgResult = dlg.ShowDialog(); switch (dlgResult) { case DialogResult.Yes: Options.ReadOnlyFileHandling = 0; // Yes break; case DialogResult.OK: Options.ReadOnlyFileHandling = 1; // Yes to All break; case DialogResult.No: Options.ReadOnlyFileHandling = 2; // No break; case DialogResult.Cancel: Options.ReadOnlyFileHandling = 3; // No to All break; } } if (track.Readonly) { if (!Options.MainSettings.ChangeReadOnlyAttributte && Options.ReadOnlyFileHandling > 1) { errorMessage = "File is readonly"; return(false); } try { System.IO.File.SetAttributes(track.FullFileName, System.IO.File.GetAttributes(track.FullFileName) & ~FileAttributes.ReadOnly); track.Readonly = false; } catch (Exception ex) { log.Error("File Save: Can't reset Readonly attribute: {0} {1}", track.FullFileName, ex.Message); errorMessage = ServiceScope.Get <ILocalisation>().ToString("message", "ErrorResetAttr"); return(false); } } TagLib.File file = null; bool error = false; try { TagLib.ByteVector.UseBrokenLatin1Behavior = true; file = TagLib.File.Create(track.FullFileName); } catch (CorruptFileException) { log.Warn("File Read: Ignoring track {0} - Corrupt File!", track.FullFileName); errorMessage = ServiceScope.Get <ILocalisation>().ToString("message", "CorruptFile"); error = true; } catch (UnsupportedFormatException) { log.Warn("File Read: Ignoring track {0} - Unsupported format!", track.FullFileName); errorMessage = ServiceScope.Get <ILocalisation>().ToString("message", "UnsupportedFormat"); error = true; } catch (FileNotFoundException) { log.Warn("File Read: Ignoring track {0} - Physical file no longer existing!", track.FullFileName); errorMessage = ServiceScope.Get <ILocalisation>().ToString("message", "NonExistingFile"); error = true; } catch (Exception ex) { log.Error("File Read: Error processing file: {0} {1}", track.FullFileName, ex.Message); errorMessage = string.Format(ServiceScope.Get <ILocalisation>().ToString("message", "ErrorReadingFile"), ex.Message); error = true; } if (file == null || error) { log.Error("File Read: Error processing file.: {0}", track.FullFileName); return(false); } try { // Get the ID3 Frame for ID3 specifc frame handling TagLib.Id3v1.Tag id3v1tag = null; TagLib.Id3v2.Tag id3v2tag = null; if (track.IsMp3) { id3v1tag = file.GetTag(TagTypes.Id3v1, true) as TagLib.Id3v1.Tag; id3v2tag = file.GetTag(TagTypes.Id3v2, true) as TagLib.Id3v2.Tag; } // Remove Tags, if they have been removed in TagEdit Panel foreach (TagLib.TagTypes tagType in track.TagsRemoved) { file.RemoveTags(tagType); } #region Main Tags string[] splitValues = track.Artist.Split(new[] { ';', '|' }); file.Tag.Performers = splitValues; splitValues = track.AlbumArtist.Split(new[] { ';', '|' }); file.Tag.AlbumArtists = splitValues; file.Tag.Album = track.Album.Trim(); file.Tag.BeatsPerMinute = (uint)track.BPM; if (track.Comment != "") { file.Tag.Comment = ""; if (track.IsMp3) { id3v1tag.Comment = track.Comment; foreach (Comment comment in track.ID3Comments) { CommentsFrame commentsframe = CommentsFrame.Get(id3v2tag, comment.Description, comment.Language, true); commentsframe.Text = comment.Text; commentsframe.Description = comment.Description; commentsframe.Language = comment.Language; } } else { file.Tag.Comment = track.Comment; } } else { file.Tag.Comment = ""; } if (track.IsMp3) { id3v2tag.IsCompilation = track.Compilation; } file.Tag.Disc = track.DiscNumber; file.Tag.DiscCount = track.DiscCount; splitValues = track.Genre.Split(new[] { ';', '|' }); file.Tag.Genres = splitValues; file.Tag.Title = track.Title; file.Tag.Track = track.TrackNumber; file.Tag.TrackCount = track.TrackCount; file.Tag.Year = (uint)track.Year; file.Tag.ReplayGainTrack = track.ReplayGainTrack; file.Tag.ReplayGainTrackPeak = track.ReplayGainTrackPeak; file.Tag.ReplayGainAlbum = track.ReplayGainAlbum; file.Tag.ReplayGainAlbumPeak = track.ReplayGainAlbumPeak; #endregion #region Detailed Information splitValues = track.Composer.Split(new[] { ';', '|' }); file.Tag.Composers = splitValues; file.Tag.Conductor = track.Conductor; file.Tag.Copyright = track.Copyright; file.Tag.Grouping = track.Grouping; splitValues = track.ArtistSortName.Split(new[] { ';', '|' }); file.Tag.PerformersSort = splitValues; splitValues = track.AlbumArtistSortName.Split(new[] { ';', '|' }); file.Tag.AlbumArtistsSort = splitValues; file.Tag.AlbumSort = track.AlbumSortName; file.Tag.TitleSort = track.TitleSortName; #endregion #region Picture List <TagLib.Picture> pics = new List <TagLib.Picture>(); foreach (Picture pic in track.Pictures) { TagLib.Picture tagPic = new TagLib.Picture(); try { byte[] byteArray = pic.Data; ByteVector data = new ByteVector(byteArray); tagPic.Data = data; tagPic.Description = pic.Description; tagPic.MimeType = "image/jpg"; tagPic.Type = pic.Type; pics.Add(tagPic); } catch (Exception ex) { log.Error("Error saving Picture: {0}", ex.Message); } file.Tag.Pictures = pics.ToArray(); } // Clear the picture if (track.Pictures.Count == 0) { file.Tag.Pictures = pics.ToArray(); } #endregion #region Lyrics if (track.Lyrics != null && track.Lyrics != "") { file.Tag.Lyrics = track.Lyrics; if (track.IsMp3) { foreach (Lyric lyric in track.LyricsFrames) { UnsynchronisedLyricsFrame lyricframe = UnsynchronisedLyricsFrame.Get(id3v2tag, lyric.Description, lyric.Language, true); lyricframe.Text = lyric.Text; lyricframe.Description = lyric.Description; lyricframe.Language = lyric.Language; } } else { file.Tag.Lyrics = track.Lyrics; } } else { file.Tag.Lyrics = ""; } #endregion #region Ratings if (track.IsMp3) { if (track.Ratings.Count > 0) { foreach (PopmFrame rating in track.Ratings) { PopularimeterFrame popmFrame = PopularimeterFrame.Get(id3v2tag, rating.User, true); popmFrame.Rating = Convert.ToByte(rating.Rating); popmFrame.PlayCount = Convert.ToUInt32(rating.PlayCount); } } else { id3v2tag.RemoveFrames("POPM"); } } else if (track.TagType == "ogg" || track.TagType == "flac") { if (track.Ratings.Count > 0) { XiphComment xiph = file.GetTag(TagLib.TagTypes.Xiph, true) as XiphComment; xiph.SetField("RATING", track.Rating.ToString()); } } #endregion #region Non- Standard Taglib and User Defined Frames if (Options.MainSettings.ClearUserFrames) { foreach (Frame frame in track.UserFrames) { ByteVector frameId = new ByteVector(frame.Id); if (frame.Id == "TXXX") { id3v2tag.SetUserTextAsString(frame.Description, ""); } else { id3v2tag.SetTextFrame(frameId, ""); } } } List <Frame> allFrames = new List <Frame>(); allFrames.AddRange(track.Frames); // The only way to avoid duplicates of User Frames is to delete them by assigning blank values to them if (track.SavedUserFrames != null && !Options.MainSettings.ClearUserFrames) { // Clean the previously saved Userframes, to avoid duplicates foreach (Frame frame in track.SavedUserFrames) { ByteVector frameId = new ByteVector(frame.Id); if (frame.Id == "TXXX") { id3v2tag.SetUserTextAsString(frame.Description, ""); } else { id3v2tag.SetTextFrame(frameId, ""); } } allFrames.AddRange(track.UserFrames); } foreach (Frame frame in allFrames) { ByteVector frameId = new ByteVector(frame.Id); // The only way to avoid duplicates of User Frames is to delete them by assigning blank values to them if (frame.Id == "TXXX") { if (frame.Description != "") { id3v2tag.SetUserTextAsString(frame.Description, ""); id3v2tag.SetUserTextAsString(frame.Description, frame.Value); } } else { id3v2tag.SetTextFrame(frameId, ""); id3v2tag.SetTextFrame(frameId, frame.Value); } } #endregion // Now, depending on which frames the user wants to save, we will remove the other Frames file = Util.FormatID3Tag(file); // Set the encoding for ID3 Tags if (track.IsMp3) { TagLib.Id3v2.Tag.ForceDefaultEncoding = true; switch (Options.MainSettings.CharacterEncoding) { case 0: TagLib.Id3v2.Tag.DefaultEncoding = StringType.Latin1; break; case 1: TagLib.Id3v2.Tag.DefaultEncoding = StringType.UTF16; break; case 2: TagLib.Id3v2.Tag.DefaultEncoding = StringType.UTF16BE; break; case 3: TagLib.Id3v2.Tag.DefaultEncoding = StringType.UTF8; break; case 4: TagLib.Id3v2.Tag.DefaultEncoding = StringType.UTF16LE; break; } } // Save the file file.Save(); } catch (Exception ex) { log.Error("File Save: Error processing file: {0} {1}", track.FullFileName, ex.Message); errorMessage = ServiceScope.Get <ILocalisation>().ToString("message", "ErrorSave"); error = true; } if (error) { return(false); } return(true); }
/// <summary> /// Based on the Options set, use the correct version for ID3 /// Eventually remove V1 or V2 tags, if set in the options /// </summary> /// <param name = "File"></param> public static File FormatID3Tag(File file) { if (file.MimeType == "taglib/mp3") { Tag id3v2_tag = file.GetTag(TagTypes.Id3v2) as Tag; if (id3v2_tag != null && Options.MainSettings.ID3V2Version > 0) id3v2_tag.Version = (byte)Options.MainSettings.ID3V2Version; // Remove V1 Tags, if checked or "Save V2 only checked" if (Options.MainSettings.RemoveID3V1 || Options.MainSettings.ID3Version == 2) file.RemoveTags(TagTypes.Id3v1); // Remove V2 Tags, if checked or "Save V1 only checked" if (Options.MainSettings.RemoveID3V2 || Options.MainSettings.ID3Version == 1) file.RemoveTags(TagTypes.Id3v2); // Remove V2 Tags, if Ape checked if (Options.MainSettings.ID3V2Version == 0) { file.RemoveTags(TagTypes.Id3v2); } else { file.RemoveTags(TagTypes.Ape); } } return file; }
public static void Main(string [] args) { if (args.Length < 3) { Console.Error.WriteLine("USAGE: BatchSet.exe -tag value [-tag2 value ...] File1 [File2 ...]"); return; } Mode mode = Mode.Tag; List <string> files = new List <string> (); Dictionary <string, string> tags = new Dictionary <string, string> (); string tag = null; foreach (string str in args) { if (mode == Mode.Tag) { if (str [0] == '-') { if (str == "--") { mode = Mode.File; } else { tag = str.Substring(1); mode = Mode.Value; } continue; } mode = Mode.File; } if (mode == Mode.Value) { if (!tags.ContainsKey(tag)) { tags.Add(tag, str); } mode = Mode.Tag; continue; } if (mode == Mode.File) { files.Add(str); } } foreach (string filename in files) { TagLib.File file = TagLib.File.Create(filename); if (file == null) { continue; } Console.WriteLine("Updating Tags For: " + filename); foreach (string key in tags.Keys) { string value = tags [key]; try { switch (key) { case "id3version": byte number = byte.Parse(value); if (number == 1) { file.RemoveTags(TagTypes.Id3v2); } else { TagLib.Id3v2.Tag v2 = file.GetTag(TagTypes.Id3v2, true) as TagLib.Id3v2.Tag; if (v2 != null) { v2.Version = number; } } break; case "album": file.Tag.Album = value; break; case "artists": file.Tag.AlbumArtists = value.Split(new char [] { ';' }); break; case "comment": file.Tag.Comment = value; break; case "lyrics": file.Tag.Lyrics = value; break; case "composers": file.Tag.Composers = value.Split(new char [] { ';' }); break; case "disc": file.Tag.Disc = uint.Parse(value); break; case "disccount": file.Tag.DiscCount = uint.Parse(value); break; case "genres": file.Tag.Genres = value.Split(new char [] { ';' }); break; case "performers": file.Tag.Performers = value.Split(new char [] { ';' }); break; case "title": file.Tag.Title = value; break; case "track": file.Tag.Track = uint.Parse(value); break; case "trackcount": file.Tag.TrackCount = uint.Parse(value); break; case "year": file.Tag.Year = uint.Parse(value); break; case "pictures": List <Picture> pics = new List <Picture> (); if (!string.IsNullOrEmpty(value)) { foreach (string path in value.Split(new char [] { ';' })) { pics.Add(new Picture(path)); } } file.Tag.Pictures = pics.ToArray(); break; } } catch (Exception e) { Console.WriteLine("Error setting tag " + key + ":"); Console.WriteLine(e); } } file.Save(); } }
/// <summary> /// Save the Modified file /// </summary> /// <param name="song"></param> /// <param name="errorMessage"></param> /// <returns></returns> public static bool SaveFile(SongData song, ref string errorMessage) { errorMessage = ""; if (!song.Changed) { return(true); } var options = (ServiceLocator.Current.GetInstance(typeof(ISettingsManager)) as ISettingsManager)?.GetOptions; /* * if (song.Readonly && !options.MainSettings.ChangeReadOnlyAttributte && * (options.ReadOnlyFileHandling == 0 || options.ReadOnlyFileHandling == 2)) * { * Form dlg = new ReadOnlyDialog(song.FullFileName); * DialogResult dlgResult = dlg.ShowDialog(); * * switch (dlgResult) * { * case DialogResult.Yes: * options.ReadOnlyFileHandling = 0; // Yes * break; * * case DialogResult.OK: * options.ReadOnlyFileHandling = 1; // Yes to All * break; * * case DialogResult.No: * options.ReadOnlyFileHandling = 2; // No * break; * * case DialogResult.Cancel: * options.ReadOnlyFileHandling = 3; // No to All * break; * } * } */ if (song.Readonly) { if (!options.MainSettings.ChangeReadOnlyAttribute && options.ReadOnlyFileHandling > 1) { errorMessage = "File is readonly"; return(false); } try { System.IO.File.SetAttributes(song.FullFileName, System.IO.File.GetAttributes(song.FullFileName) & ~FileAttributes.ReadOnly); song.Readonly = false; } catch (Exception ex) { log.Error($"File Save: Can't reset Readonly attribute: {song.FullFileName} {ex.Message}"); errorMessage = LocalizeDictionary.Instance.GetLocalizedObject("MPTagThat", "Strings", "message_ErrorResetAttr", LocalizeDictionary.Instance.Culture).ToString(); return(false); } } TagLib.File file = null; bool error = false; try { TagLib.ByteVector.UseBrokenLatin1Behavior = true; file = TagLib.File.Create(song.FullFileName); } catch (CorruptFileException) { log.Warn($"File Read: Ignoring song {song.FullFileName} - Corrupt File!"); errorMessage = LocalizeDictionary.Instance.GetLocalizedObject("MPTagThat", "Strings", "message_CorruptFile", LocalizeDictionary.Instance.Culture).ToString(); error = true; } catch (UnsupportedFormatException) { log.Warn($"File Read: Ignoring song {song.FullFileName} - Unsupported format!"); errorMessage = LocalizeDictionary.Instance.GetLocalizedObject("MPTagThat", "Strings", "message_UnsupportedFormat", LocalizeDictionary.Instance.Culture).ToString(); error = true; } catch (FileNotFoundException) { log.Warn($"File Read: Ignoring song {song.FullFileName} - Physical file no longer existing!"); errorMessage = LocalizeDictionary.Instance.GetLocalizedObject("MPTagThat", "Strings", "message_NonExistingFile", LocalizeDictionary.Instance.Culture).ToString(); error = true; } catch (Exception ex) { log.Error($"File Read: Error processing file: {song.FullFileName} {ex.Message}"); errorMessage = string.Format(LocalizeDictionary.Instance.GetLocalizedObject("MPTagThat", "Strings", "message_ErrorReadingFile", LocalizeDictionary.Instance.Culture).ToString(), song.FullFileName); error = true; } if (file == null || error) { log.Error("File Read: Error processing file.: {0}", song.FullFileName); return(false); } try { // Get the ID3 Frame for ID3 specifc frame handling TagLib.Id3v1.Tag id3v1tag = null; TagLib.Id3v2.Tag id3v2tag = null; if (song.IsMp3) { id3v1tag = file.GetTag(TagTypes.Id3v1, true) as TagLib.Id3v1.Tag; id3v2tag = file.GetTag(TagTypes.Id3v2, true) as TagLib.Id3v2.Tag; } // Remove Tags, if they have been removed in TagEdit Panel foreach (TagLib.TagTypes tagType in song.TagsRemoved) { file.RemoveTags(tagType); } if (file.Tag != null) { #region Main Tags string[] splitValues = song.Artist.Split(new[] { ';', '|' }); file.Tag.Performers = splitValues; splitValues = song.AlbumArtist.Split(new[] { ';', '|' }); file.Tag.AlbumArtists = splitValues; file.Tag.Album = song.Album.Trim(); file.Tag.BeatsPerMinute = (uint)song.BPM; if (song.Comment != "") { file.Tag.Comment = ""; if (song.IsMp3) { id3v1tag.Comment = song.Comment; foreach (Comment comment in song.ID3Comments) { CommentsFrame commentsframe = CommentsFrame.Get(id3v2tag, comment.Description, comment.Language, true); commentsframe.Text = comment.Text; commentsframe.Description = comment.Description; commentsframe.Language = comment.Language; } } else { file.Tag.Comment = song.Comment; } } else { if (song.IsMp3 && id3v2tag != null) { id3v2tag.RemoveFrames("COMM"); } else { file.Tag.Comment = ""; } } if (song.IsMp3) { id3v2tag.IsCompilation = song.Compilation; } file.Tag.Disc = song.DiscNumber; file.Tag.DiscCount = song.DiscCount; splitValues = song.Genre.Split(new[] { ';', '|' }); file.Tag.Genres = splitValues; file.Tag.Title = song.Title; file.Tag.Track = song.TrackNumber; file.Tag.TrackCount = song.TrackCount; file.Tag.Year = (uint)song.Year; double gain; var replayGainTrack = string.IsNullOrEmpty(song.ReplayGainTrack) ? "" : song.ReplayGainTrack.Substring(0, song.ReplayGainTrack.IndexOf(" ", StringComparison.Ordinal)); if (double.TryParse(replayGainTrack, NumberStyles.Any, CultureInfo.InvariantCulture, out gain)) { file.Tag.ReplayGainTrackGain = gain; } if (Double.TryParse(song.ReplayGainTrackPeak, NumberStyles.Any, CultureInfo.InvariantCulture, out gain)) { file.Tag.ReplayGainTrackPeak = gain; } var replayGainAlbum = string.IsNullOrEmpty(song.ReplayGainAlbum) ? "" : song.ReplayGainAlbum.Substring(0, song.ReplayGainAlbum.IndexOf(" ", StringComparison.Ordinal)); if (Double.TryParse(replayGainAlbum, NumberStyles.Any, CultureInfo.InvariantCulture, out gain)) { file.Tag.ReplayGainAlbumGain = gain; } if (Double.TryParse(song.ReplayGainAlbumPeak, NumberStyles.Any, CultureInfo.InvariantCulture, out gain)) { file.Tag.ReplayGainAlbumPeak = gain; } #endregion #region MusicBrainz file.Tag.MusicBrainzArtistId = song.MusicBrainzArtistId; file.Tag.MusicBrainzDiscId = song.MusicBrainzDiscId; file.Tag.MusicBrainzReleaseArtistId = song.MusicBrainzReleaseArtistId; file.Tag.MusicBrainzReleaseCountry = song.MusicBrainzReleaseCountry; file.Tag.MusicBrainzReleaseGroupId = song.MusicBrainzReleaseGroupId; file.Tag.MusicBrainzReleaseId = song.MusicBrainzReleaseId; file.Tag.MusicBrainzReleaseStatus = song.MusicBrainzReleaseStatus; file.Tag.MusicBrainzTrackId = song.MusicBrainzTrackId; file.Tag.MusicBrainzReleaseType = song.MusicBrainzReleaseType; #endregion #region Detailed Information splitValues = song.Composer.Split(new[] { ';', '|' }); file.Tag.Composers = splitValues; file.Tag.Conductor = song.Conductor; file.Tag.Copyright = song.Copyright; file.Tag.Grouping = song.Grouping; splitValues = song.ArtistSortName.Split(new[] { ';', '|' }); file.Tag.PerformersSort = splitValues; splitValues = song.AlbumArtistSortName.Split(new[] { ';', '|' }); file.Tag.AlbumArtistsSort = splitValues; file.Tag.AlbumSort = song.AlbumSortName; file.Tag.TitleSort = song.TitleSortName; #endregion #region Picture List <TagLib.Picture> pics = new List <TagLib.Picture>(); foreach (Picture pic in song.Pictures) { TagLib.Picture tagPic = new TagLib.Picture(); try { byte[] byteArray = pic.Data; ByteVector data = new ByteVector(byteArray); tagPic.Data = data; tagPic.Description = pic.Description; tagPic.MimeType = "image/jpg"; tagPic.Type = pic.Type; pics.Add(tagPic); } catch (Exception ex) { log.Error("Error saving Picture: {0}", ex.Message); } file.Tag.Pictures = pics.ToArray(); } // Clear the picture if (song.Pictures.Count == 0) { file.Tag.Pictures = pics.ToArray(); } #endregion #region Lyrics if (song.Lyrics != null && song.Lyrics != "") { file.Tag.Lyrics = song.Lyrics; if (song.IsMp3) { id3v2tag.RemoveFrames("USLT"); foreach (Lyric lyric in song.LyricsFrames) { UnsynchronisedLyricsFrame lyricframe = UnsynchronisedLyricsFrame.Get(id3v2tag, lyric.Description, lyric.Language, true); lyricframe.Text = lyric.Text; lyricframe.Description = lyric.Description; lyricframe.Language = lyric.Language; } } else { file.Tag.Lyrics = song.Lyrics; } } else { file.Tag.Lyrics = ""; } #endregion #region Ratings if (song.IsMp3) { id3v2tag.RemoveFrames("POPM"); if (song.Ratings.Count > 0) { foreach (PopmFrame rating in song.Ratings) { PopularimeterFrame popmFrame = PopularimeterFrame.Get(id3v2tag, rating.User, true); popmFrame.Rating = Convert.ToByte(rating.Rating); popmFrame.PlayCount = Convert.ToUInt32(rating.PlayCount); } } } else if (song.TagType == "ogg" || song.TagType == "flac") { if (song.Ratings.Count > 0) { XiphComment xiph = file.GetTag(TagLib.TagTypes.Xiph, true) as XiphComment; xiph.SetField("RATING", song.Rating.ToString()); } } #endregion #region Non- Standard Taglib and User Defined Frames if (options.MainSettings.ClearUserFrames) { foreach (Frame frame in song.UserFrames) { ByteVector frameId = new ByteVector(frame.Id); if (frame.Id == "TXXX") { id3v2tag.SetUserTextAsString(frame.Description, "", true); } else { id3v2tag.SetTextFrame(frameId, ""); } } } List <Frame> allFrames = new List <Frame>(); allFrames.AddRange(song.Frames); // The only way to avoid duplicates of User Frames is to delete them by assigning blank values to them if (song.SavedUserFrames != null && !options.MainSettings.ClearUserFrames) { // Clean the previously saved Userframes, to avoid duplicates foreach (Frame frame in song.SavedUserFrames) { ByteVector frameId = new ByteVector(frame.Id); if (frame.Id == "TXXX") { id3v2tag.SetUserTextAsString(frame.Description, "", true); } else { id3v2tag.SetTextFrame(frameId, ""); } } allFrames.AddRange(song.UserFrames); } foreach (Frame frame in allFrames) { ByteVector frameId = new ByteVector(frame.Id); // The only way to avoid duplicates of User Frames is to delete them by assigning blank values to them if (frame.Id == "TXXX") { if (frame.Description != "") { id3v2tag.SetUserTextAsString(frame.Description, "", true); id3v2tag.SetUserTextAsString(frame.Description, frame.Value, true); } } else { id3v2tag.SetTextFrame(frameId, ""); id3v2tag.SetTextFrame(frameId, frame.Value); } } #endregion // Now, depending on which frames the user wants to save, we will remove the other Frames file = Util.FormatID3Tag(file); // Set the encoding for ID3 Tags if (song.IsMp3) { TagLib.Id3v2.Tag.ForceDefaultEncoding = true; switch (options.MainSettings.CharacterEncoding) { case "Latin1": TagLib.Id3v2.Tag.DefaultEncoding = StringType.Latin1; break; case "UTF16": TagLib.Id3v2.Tag.DefaultEncoding = StringType.UTF16; break; case "UTF16-BE": TagLib.Id3v2.Tag.DefaultEncoding = StringType.UTF16BE; break; case "UTF8": TagLib.Id3v2.Tag.DefaultEncoding = StringType.UTF8; break; case "UTF16-LE": TagLib.Id3v2.Tag.DefaultEncoding = StringType.UTF16LE; break; } } } // Save the file file.Save(); } catch (Exception ex) { log.Error("File Save: Error processing file: {0} {1}", song.FullFileName, ex.Message); errorMessage = string.Format(LocalizeDictionary.Instance.GetLocalizedObject("MPTagThat", "Strings", "message_ErrorSave", LocalizeDictionary.Instance.Culture).ToString(), song.FullFileName); error = true; } if (error) { return(false); } return(true); }
public static TagLib.File ConvertMusicFileTagToTag(MusicFileTag musicTag) { TagLib.File tagInfo = TagLib.File.Create(musicTag.FilePath); // V1 if (!musicTag.EnabledV1) { tagInfo.RemoveTags(TagTypes.Id3v1); } else { tagInfo.GetTag(TagTypes.Id3v1).Performers = new string[] { musicTag.ArtistV1 ?? "" }; tagInfo.GetTag(TagTypes.Id3v1).Genres = new string[] { musicTag.GenreV1 ?? "" }; tagInfo.GetTag(TagTypes.Id3v1).Album = musicTag.AlbumV1 ?? ""; tagInfo.GetTag(TagTypes.Id3v1).Title = musicTag.TitleV1 ?? ""; tagInfo.GetTag(TagTypes.Id3v1).Comment = musicTag.CommentV1 ?? ""; int.TryParse(musicTag.YearV1, out int tmpYearV1); if (tmpYearV1 > 0) { tagInfo.GetTag(TagTypes.Id3v1).Year = (uint)tmpYearV1; } int.TryParse(musicTag.TrackV1, out int tmpTrackV1); if (tmpTrackV1 > 0) { tagInfo.GetTag(TagTypes.Id3v1).Track = (uint)tmpTrackV1; } } // V2 if (!musicTag.EnabledV2) { tagInfo.RemoveTags(TagTypes.Id3v2); } else { TagLib.Id3v2.Tag id3v2Tag = tagInfo.GetTag(TagTypes.Id3v2) as TagLib.Id3v2.Tag; id3v2Tag.Version = Convert.ToByte(musicTag.VersionV2); id3v2Tag.SetTextFrame("TDLY", musicTag.PlayListDelayV2); id3v2Tag.SetTextFrame("TRCK", musicTag.TrackNumberV2); id3v2Tag.SetTextFrame("TPOS", musicTag.PartOfSetV2); id3v2Tag.SetTextFrame("TBPM", musicTag.BPMV2); id3v2Tag.SetTextFrame("TPE1", musicTag.ArtistV2); id3v2Tag.SetTextFrame("TCON", musicTag.GenreV2); id3v2Tag.SetTextFrame("TLAN", musicTag.LanguageV2); id3v2Tag.SetTextFrame("TKEY", musicTag.KeyV2); id3v2Tag.SetTextFrame("TSST", musicTag.SetSubtitleV2); id3v2Tag.SetTextFrame("TIT1", musicTag.ContentDescriptionV2); id3v2Tag.SetTextFrame("TMOO", musicTag.MoodV2); id3v2Tag.SetTextFrame("TPE4", musicTag.InterpretedV2); id3v2Tag.SetTextFrame("TSOA", musicTag.AlbumSortV2); id3v2Tag.SetTextFrame("TALB", musicTag.AlbumV2); id3v2Tag.SetTextFrame("TIT3", musicTag.SubtitleV2); id3v2Tag.SetTextFrame("TSOT", musicTag.TitleSortV2); id3v2Tag.SetTextFrame("TIT2", musicTag.TitleV2); /// Frames from /// http://id3.org/id3v2.3.0#Declared_ID3v2_frames } return(tagInfo); }
/// <summary> /// Clears all file meta data. /// </summary> public void clearMetaData() { file.RemoveTags(TagTypes.Id3v2); }