/// <summary> /// Copies the values from the current instance to another /// <see cref="TagLib.Tag" />, optionally overwriting /// existing values. /// </summary> /// <param name="target"> /// A <see cref="TagLib.Tag" /> object containing the target /// tag to copy values to. /// </param> /// <param name="overwrite"> /// A <see cref="bool" /> specifying whether or not to copy /// values over existing one. /// </param> /// <remarks> /// <para>If <paramref name="target" /> is of type <see /// cref="TagLib.Ape.Tag" /> a complete copy of all values /// will be performed. Otherwise, only standard values will /// be copied.</para> /// </remarks> /// <exception cref="ArgumentNullException"> /// <paramref name="target" /> is <see langword="null" />. /// </exception> public override void CopyTo(TagLib.Tag target, bool overwrite) { if (target == null) { throw new ArgumentNullException("target"); } TagLib.Ape.Tag match = target as TagLib.Ape.Tag; if (match == null) { base.CopyTo(target, overwrite); return; } foreach (Item item in items) { if (!overwrite && match.GetItem(item.Key) != null) { continue; } match.items.Add(item.Clone()); } }
/// <summary> /// Reads a tag ending at a specified position and moves the /// cursor to its start position. /// </summary> /// <param name="end"> /// A <see cref="long" /> value reference specifying at what /// position the potential tag ends at. If a tag is found, /// this value will be updated to the position at which the /// found tag starts. /// </param> /// <returns> /// A <see cref="TagLib.Tag" /> object representing the tag /// found at the specified position, or <see langword="null" /// /> if no tag was found. /// </returns> private TagLib.Tag ReadTag(ref long end) { long start = end; TagTypes type = ReadTagInfo(ref start); TagLib.Tag tag = null; try { switch (type) { case TagTypes.Ape: tag = new TagLib.Ape.Tag(file, end - TagLib.Ape.Footer.Size); break; case TagTypes.Id3v2: tag = new TagLib.Id3v2.Tag(file, start); break; case TagTypes.Id3v1: tag = new TagLib.Id3v1.Tag(file, start); break; } end = start; } catch (CorruptFileException) { } return(tag); }
/// <summary> /// Reads a tag starting at a specified position and moves the /// cursor to its start position. /// </summary> /// <param name="start"> /// A <see cref="long" /> value reference specifying at what /// position the potential tag starts. If a tag is found, /// this value will be updated to the position at which the /// found tag ends. /// </param> /// <returns> /// A <see cref="TagLib.Tag" /> object representing the tag /// found at the specified position, or <see langword="null" /// /> if no tag was found. /// </returns> private TagLib.Tag ReadTag(ref long start) { long end = start; TagTypes type = ReadTagInfo(ref end); TagLib.Tag tag = null; try { switch (type) { case TagTypes.Ape: tag = new TagLib.Ape.Tag(file, start); break; case TagTypes.Id3v2: tag = new TagLib.Id3v2.Tag(file, start); break; } } catch (CorruptFileException e) { Console.Error.WriteLine("taglib-sharp caught exception creating tag: {0}", e); } start = end; return(tag); }
public void TestAlbumArtists() { Tag tag = new Tag(); TagTestWithSave(ref tag, delegate(Tag t, string m) { Assert.IsTrue(t.IsEmpty, "Initial (IsEmpty): " + m); Assert.AreEqual(0, t.AlbumArtists.Length, "Initial (Zero): " + m); }); tag.AlbumArtists = val_mult; TagTestWithSave(ref tag, delegate(Tag t, string m) { Assert.IsFalse(t.IsEmpty, "Value Set (!IsEmpty): " + m); Assert.AreEqual(val_mult.Length, t.AlbumArtists.Length, "Value Set: " + m); for (int i = 0; i < val_mult.Length; i++) { Assert.AreEqual(val_mult[i], t.AlbumArtists[i], "Value Set: " + m); } }); tag.AlbumArtists = new string[0]; TagTestWithSave(ref tag, delegate(Tag t, string m) { Assert.IsTrue(t.IsEmpty, "Value Cleared (IsEmpty): " + m); Assert.AreEqual(0, t.AlbumArtists.Length, "Value Cleared (Zero): " + m); }); }
public TagLib.Tag AddTag(TagTypes type, TagLib.Tag copy) { TagLib.Tag tag = null; if (type == TagTypes.Id3v1) { tag = new TagLib.Id3v1.Tag(); } else if (type == TagTypes.Id3v2) { Id3v2.Tag tag32 = new Id3v2.Tag(); tag32.Version = 4; tag32.Flags |= Id3v2.HeaderFlags.FooterPresent; tag = tag32; } else if (type == TagTypes.Ape) { tag = new TagLib.Ape.Tag(); } if (tag != null) { if (copy != null) { copy.CopyTo(tag, true); } if (type == TagTypes.Id3v1) { AddTag(tag); } else { InsertTag(0, tag); } } return(tag); }
/// <summary> /// Adds a tag of a specified type to the current instance, /// optionally copying values from an existing type. /// </summary> /// <param name="type"> /// A <see cref="TagTypes" /> value specifying the type of /// tag to add to the current instance. At the time of this /// writing, this is limited to <see cref="TagTypes.Ape" /> /// and <see cref="TagTypes.Id3v2" />. /// </param> /// <param name="copy"> /// A <see cref="TagLib.Tag" /> to copy values from using /// <see cref="TagLib.Tag.CopyTo" />, or <see /// langword="null" /> if no tag is to be copied. /// </param> /// <returns> /// The <see cref="TagLib.Tag" /> object added to the current /// instance, or <see langref="null" /> if it couldn't be /// created. /// </returns> /// <remarks> /// ID3v2 tags are added at the end of the current instance, /// while other tags are added to the beginning. /// </remarks> public TagLib.Tag AddTag(TagTypes type, TagLib.Tag copy) { TagLib.Tag tag = null; if (type == TagTypes.Id3v2) { tag = new TagLib.Id3v2.Tag(); } else if (type == TagTypes.Ape) { tag = new TagLib.Ape.Tag(); (tag as Ape.Tag).HeaderPresent = true; } if (tag != null) { if (copy != null) { copy.CopyTo(tag, true); } AddTag(tag); } return(tag); }
//Collects the stacks saved in the mp3 file. saves them in the printouts folder. public static string ReturnCloudCoinStack(TagLib.File Mp3File) { TagLib.Ape.Tag ApeTag = Mp3Methods.CheckApeTag(Mp3File); TagLib.Ape.Item CCS = ApeTag.GetItem("CloudCoinStack"); TagLib.Ape.Item StackN = ApeTag.GetItem("StackName"); if (CCS != null) { string filename = StackN.ToString(); string message = "Press enter to extract the Cloudcoin stack from " + filename + "."; if (getEnter(message)) { Console.Out.WriteLine("Stack: " + filename + " has been found"); string CloudCoinAreaValues = CCS.ToString(); string path = "./Printouts/" + filename; try { System.IO.File.WriteAllText(path, CloudCoinAreaValues); //Create a document containing Mp3 ByteFile (debugging). } catch (Exception e) { Console.Out.WriteLine("Failed to save CloudCoin data {0}", e); } Console.Out.WriteLine("CCS: " + CloudCoinAreaValues); return(path); } return("null"); } else { Console.Out.WriteLine("no stack in file" + CCS); return("no .stack in file"); } }
public static bool UpdateTags(TagLib.File fileInfo, NameValueCollection tags, CUEToolsCodecsConfig config, bool useId3v24) { if (fileInfo is TagLib.Riff.File) { return(false); } TagLib.Ogg.XiphComment xiph = (TagLib.Ogg.XiphComment)fileInfo.GetTag(TagLib.TagTypes.Xiph); if (xiph != null) { foreach (string tag in tags.AllKeys) { xiph.SetField(tag, tags.GetValues(tag)); } return(true); } if (fileInfo is TagLib.Mpeg4.File) { var mpeg4 = (TagLib.Mpeg4.AppleTag)fileInfo.GetTag(TagLib.TagTypes.Apple, true); foreach (string tag in tags.AllKeys) { mpeg4.SetDashBox("com.apple.iTunes", tag, string.Join(";", tags.GetValues(tag))); } return(true); } if (fileInfo is TagLib.Mpeg.AudioFile || (fileInfo is TagLib.UserDefined.File && (fileInfo as TagLib.UserDefined.File).Tagger == CUEToolsTagger.ID3v2)) { var id3v2 = (TagLib.Id3v2.Tag)fileInfo.GetTag(TagLib.TagTypes.Id3v2, true); id3v2.Version = (byte)(useId3v24 ? 4 : 3); foreach (string tag in tags.AllKeys) { var frame = TagLib.Id3v2.UserTextInformationFrame.Get(id3v2, tag, true); frame.Text = tags.GetValues(tag); } return(true); } if (fileInfo is TagLib.Asf.File) { var asf = (TagLib.Asf.Tag)fileInfo.GetTag(TagLib.TagTypes.Asf, true); foreach (string tag in tags.AllKeys) { asf.SetDescriptorStrings(tags.GetValues(tag), "foobar2000/" + tag); } return(true); } TagLib.Ape.Tag ape = (TagLib.Ape.Tag)fileInfo.GetTag(TagLib.TagTypes.Ape, true); if (ape != null) { foreach (string tag in tags.AllKeys) { ape.SetValue(tag, tags.GetValues(tag)); } } return(true); }
/// <summary>Function to read the various tags from file, if available /// These will be checked in various get functions /// </summary> private void ReadTags() { //currentFile = TagLib.File.Create(FileInfoView.FocusedItem.SubItems[4].Text); id3v1 = currentFile.GetTag(TagLib.TagTypes.Id3v1) as TagLib.Id3v1.Tag; id3v2 = currentFile.GetTag(TagLib.TagTypes.Id3v2) as TagLib.Id3v2.Tag; apple = currentFile.GetTag(TagLib.TagTypes.Apple) as TagLib.Mpeg4.AppleTag; ape = currentFile.GetTag(TagLib.TagTypes.Ape) as TagLib.Ape.Tag; // asf = currentFile.GetTag(TagLib.TagTypes.Asf) as TagLib.Asf.Tag; ogg = currentFile.GetTag(TagLib.TagTypes.Xiph) as TagLib.Ogg.XiphComment; flac = currentFile.GetTag(TagLib.TagTypes.FlacMetadata) as TagLib.Flac.Metadata; }
//Searches for and removes the specified Key and Value. public static bool RemoveExistingStacks(TagLib.Ape.Tag ApeTag) { try{ ApeTag.RemoveItem("CloudCoinStack"); ApeTag.RemoveItem("StackName"); Console.Out.WriteLine(" stacks deleted."); } catch (Exception e) { Console.Out.WriteLine("Error: ", e); return(false); } return(true); }
///Stores the CloudCoin.stack file as the value tied to the CloudCoinStack key. public static TagLib.Ape.Tag SetApeTagValue(TagLib.Ape.Tag ApeTag, string MyCloudCoin, string stackName) { // Get the APEv2 tag if it exists. try{ TagLib.Ape.Item currentStacks = ApeTag.GetItem("CloudCoinStack"); ApeTag.SetValue("CloudCoinStack", MyCloudCoin); ApeTag.SetValue("StackName", stackName); return(ApeTag); } catch (Exception e) { Console.Out.WriteLine("The process failed: {0}", e.ToString()); return(ApeTag); } }
public void TestPictures() { var tag = new Tag(); Picture[] pictures = { new Picture(TestPath.Covers + "sample_a.png"), new Picture(TestPath.Covers + "sample_a.jpg"), new Picture(TestPath.Covers + "sample_b.png"), new Picture(TestPath.Covers + "sample_b.jpg"), new Picture(TestPath.Covers + "sample_c.png"), new Picture(TestPath.Covers + "sample_c.jpg") }; for (int i = 0; i < 6; i++) { pictures[i].Type = (PictureType)(i * 2); } pictures[3].Description = val_sing; TagTestWithSave(ref tag, delegate(Tag t, string m) { Assert.IsTrue(t.IsEmpty, "Initial (IsEmpty): " + m); Assert.AreEqual(0, t.Pictures.Length, "Initial (Zero): " + m); }); tag.Pictures = pictures; TagTestWithSave(ref tag, delegate(Tag t, string m) { Assert.IsFalse(t.IsEmpty, "Value Set (!IsEmpty): " + m); Assert.AreEqual(pictures.Length, t.Pictures.Length, "Value Set: " + m); for (int i = 0; i < pictures.Length; i++) { string msg = "Value " + i + "Set: " + m; Assert.AreEqual(pictures[i].Data, t.Pictures[i].Data, msg); Assert.AreEqual(pictures[i].Type, t.Pictures[i].Type, msg); Assert.AreEqual(pictures[i].Description, t.Pictures[i].Description, msg); Assert.AreEqual(pictures[i].MimeType, t.Pictures[i].MimeType, msg); } }); tag.Pictures = new Picture[0]; TagTestWithSave(ref tag, delegate(Tag t, string m) { Assert.IsTrue(t.IsEmpty, "Value Cleared (IsEmpty): " + m); Assert.AreEqual(0, t.Pictures.Length, "Value Cleared (Zero): " + m); }); }
public void TestClear() { Tag tag = new Tag { Title = "A", Performers = new[] { "B" }, AlbumArtists = new[] { "C" }, Composers = new[] { "D" }, Album = "E", Comment = "F", Genres = new[] { "Blues" }, Year = 123, Track = 234, TrackCount = 234, Disc = 234, DiscCount = 234, Lyrics = "G", Grouping = "H", BeatsPerMinute = 234, Conductor = "I", Copyright = "J", Pictures = new[] { new Picture(TestPath.Covers + "sample_a.png") } }; Assert.IsFalse(tag.IsEmpty, "Should be full."); tag.Clear(); Assert.IsNull(tag.Title, "Title"); Assert.AreEqual(0, tag.Performers.Length, "Performers"); Assert.AreEqual(0, tag.AlbumArtists.Length, "AlbumArtists"); Assert.AreEqual(0, tag.Composers.Length, "Composers"); Assert.IsNull(tag.Album, "Album"); Assert.IsNull(tag.Comment, "Comment"); Assert.AreEqual(0, tag.Genres.Length, "Genres"); Assert.AreEqual(0, tag.Year, "Year"); Assert.AreEqual(0, tag.Track, "Track"); Assert.AreEqual(0, tag.TrackCount, "TrackCount"); Assert.AreEqual(0, tag.Disc, "Disc"); Assert.AreEqual(0, tag.DiscCount, "DiscCount"); Assert.IsNull(tag.Lyrics, "Lyrics"); Assert.IsNull(tag.Comment, "Comment"); Assert.AreEqual(0, tag.BeatsPerMinute, "BeatsPerMinute"); Assert.IsNull(tag.Conductor, "Conductor"); Assert.IsNull(tag.Copyright, "Copyright"); Assert.AreEqual(0, tag.Pictures.Length, "Pictures"); Assert.IsTrue(tag.IsEmpty, "Should be empty."); }
private TagLib.Tag ReadTag(ref long start) { long end = start; TagTypes type = ReadTagInfo(ref end); TagLib.Tag tag = null; switch (type) { case TagTypes.Ape: tag = new TagLib.Ape.Tag(file, start); break; case TagTypes.Id3v2: tag = new TagLib.Id3v2.Tag(file, start); break; } start = end; return(tag); }
public static string[] GetMiscTag(TagLib.File file, string name) { //TagLib.Mpeg4.AppleTag apple = (TagLib.Mpeg4.AppleTag)file.GetTag(TagLib.TagTypes.Apple); //TagLib.Id3v2.Tag id3v2 = (TagLib.Id3v2.Tag)file.GetTag(TagLib.TagTypes.Id3v2); TagLib.Ogg.XiphComment xiph = (TagLib.Ogg.XiphComment)file.GetTag(TagLib.TagTypes.Xiph); TagLib.Ape.Tag ape = (TagLib.Ape.Tag)file.GetTag(TagLib.TagTypes.Ape); //if (apple != null) //{ // string[] text = apple.GetText(name); // if (text.Length != 0) // return text; //} //if (id3v2 != null) // foreach (TagLib.Id3v2.Frame f in id3v2.GetFrames()) // if (f is TagLib.Id3v2.TextInformationFrame && ((TagLib.Id3v2.TextInformationFrame)f).Text != null) // return ((TagLib.Id3v2.TextInformationFrame)f).Text; if (xiph != null) { string[] l = xiph.GetField(name); if (l != null && l.Length != 0) { return(l); } } if (ape != null) { TagLib.Ape.Item item = ape.GetItem(name); if (item != null) { return(item.ToStringArray()); } } return(null); }
public void TestMusicBrainzReleaseCountry() { Tag tag = new Tag(); TagTestWithSave(ref tag, delegate(Tag t, string m) { Assert.IsTrue(t.IsEmpty, "Initial (IsEmpty): " + m); Assert.IsNull(t.MusicBrainzReleaseCountry, "Initial (Null): " + m); }); tag.MusicBrainzReleaseCountry = val_sing; TagTestWithSave(ref tag, delegate(Tag t, string m) { Assert.IsFalse(t.IsEmpty, "Value Set (!IsEmpty): " + m); Assert.AreEqual(val_sing, t.MusicBrainzReleaseCountry, "Value Set (!Null): " + m); }); tag.MusicBrainzReleaseCountry = string.Empty; TagTestWithSave(ref tag, delegate(Tag t, string m) { Assert.IsTrue(t.IsEmpty, "Value Cleared (IsEmpty): " + m); Assert.IsNull(t.MusicBrainzReleaseCountry, "Value Cleared (Null): " + m); }); }
public void TestBeatsPerMinute() { Tag tag = new Tag(); TagTestWithSave(ref tag, delegate(Tag t, string m) { Assert.IsTrue(t.IsEmpty, "Initial (IsEmpty): " + m); Assert.AreEqual(0, tag.BeatsPerMinute, "Initial (Zero): " + m); }); tag.BeatsPerMinute = 199; TagTestWithSave(ref tag, delegate(Tag t, string m) { Assert.IsFalse(t.IsEmpty, "Value Set (!IsEmpty): " + m); Assert.AreEqual(199, tag.BeatsPerMinute, "Value Set: " + m); }); tag.BeatsPerMinute = 0; TagTestWithSave(ref tag, delegate(Tag t, string m) { Assert.IsTrue(t.IsEmpty, "Value Cleared (IsEmpty): " + m); Assert.AreEqual(0, t.BeatsPerMinute, "Value Cleared (Zero): " + m); }); }
public void TestAmazonID() { Tag tag = new Tag(); TagTestWithSave(ref tag, delegate(Tag t, string m) { Assert.IsTrue(t.IsEmpty, "Initial (IsEmpty): " + m); Assert.IsNull(t.AmazonId, "Initial (Null): " + m); }); tag.AmazonId = val_sing; TagTestWithSave(ref tag, delegate(Tag t, string m) { Assert.IsFalse(t.IsEmpty, "Value Set (!IsEmpty): " + m); Assert.AreEqual(val_sing, t.AmazonId, "Value Set (!Null): " + m); }); tag.AmazonId = string.Empty; TagTestWithSave(ref tag, delegate(Tag t, string m) { Assert.IsTrue(t.IsEmpty, "Value Cleared (IsEmpty): " + m); Assert.IsNull(t.AmazonId, "Value Cleared (Null): " + m); }); }
/// <summary> /// Read the Tags from the File /// </summary> /// <param name="fileName"></param> /// <returns></returns> public static TrackData Create(string fileName) { TrackData track = new TrackData(); TagLib.File file = null; bool error = false; try { TagLib.ByteVector.UseBrokenLatin1Behavior = true; file = TagLib.File.Create(fileName); } catch (CorruptFileException) { log.Warn("File Read: Ignoring track {0} - Corrupt File!", fileName); error = true; } catch (UnsupportedFormatException) { log.Warn("File Read: Ignoring track {0} - Unsupported format!", fileName); error = true; } catch (FileNotFoundException) { log.Warn("File Read: Ignoring track {0} - Physical file no longer existing!", fileName); error = true; } catch (Exception ex) { log.Error("File Read: Error processing file: {0} {1}", fileName, ex.Message); error = true; } if (error) { return(null); } TagLib.Id3v2.Tag id3v2tag = null; try { if (file.MimeType.Substring(file.MimeType.IndexOf("/") + 1) == "mp3") { id3v2tag = file.GetTag(TagTypes.Id3v2, false) as TagLib.Id3v2.Tag; } } catch (Exception ex) { log.Error("File Read: Error retrieving id3tag: {0} {1}", fileName, ex.Message); return(null); } #region Set Common Values FileInfo fi = new FileInfo(fileName); try { track.Id = Guid.NewGuid(); track.FullFileName = fileName; track.FileName = Path.GetFileName(fileName); track.Readonly = fi.IsReadOnly; track.TagType = file.MimeType.Substring(file.MimeType.IndexOf("/") + 1); } catch (Exception ex) { log.Error("File Read: Error setting Common tags: {0} {1}", fileName, ex.Message); return(null); } #endregion #region Set Tags try { // Artist track.Artist = String.Join(";", file.Tag.Performers); if (track.Artist.Contains("AC;DC")) { track.Artist = track.Artist.Replace("AC;DC", "AC/DC"); } track.ArtistSortName = String.Join(";", file.Tag.PerformersSort); if (track.ArtistSortName.Contains("AC;DC")) { track.ArtistSortName = track.ArtistSortName.Replace("AC;DC", "AC/DC"); } track.AlbumArtist = String.Join(";", file.Tag.AlbumArtists); if (track.AlbumArtist.Contains("AC;DC")) { track.AlbumArtist = track.AlbumArtist.Replace("AC;DC", "AC/DC"); } track.AlbumArtistSortName = String.Join(";", file.Tag.AlbumArtistsSort); if (track.AlbumArtistSortName.Contains("AC;DC")) { track.AlbumArtistSortName = track.AlbumArtistSortName.Replace("AC;DC", "AC/DC"); } track.Album = file.Tag.Album ?? ""; track.AlbumSortName = file.Tag.AlbumSort ?? ""; track.BPM = (int)file.Tag.BeatsPerMinute; track.Compilation = id3v2tag == null ? false : id3v2tag.IsCompilation; track.Composer = string.Join(";", file.Tag.Composers); track.Conductor = file.Tag.Conductor ?? ""; track.Copyright = file.Tag.Copyright ?? ""; track.DiscNumber = file.Tag.Disc; track.DiscCount = file.Tag.DiscCount; track.Genre = string.Join(";", file.Tag.Genres); track.Grouping = file.Tag.Grouping ?? ""; track.Title = file.Tag.Title ?? ""; track.TitleSortName = file.Tag.TitleSort ?? ""; track.ReplayGainTrack = file.Tag.ReplayGainTrack ?? ""; track.ReplayGainTrackPeak = file.Tag.ReplayGainTrackPeak ?? ""; track.ReplayGainAlbum = file.Tag.ReplayGainAlbum ?? ""; track.ReplayGainAlbumPeak = file.Tag.ReplayGainAlbumPeak ?? ""; track.TrackNumber = file.Tag.Track; track.TrackCount = file.Tag.TrackCount; track.Year = (int)file.Tag.Year; // Pictures foreach (IPicture picture in file.Tag.Pictures) { MPTagThat.Core.Common.Picture pic = new MPTagThat.Core.Common.Picture { Type = picture.Type, MimeType = picture.MimeType, Description = picture.Description }; pic.Data = picture.Data.Data; track.Pictures.Add(pic); } // Comments if (track.IsMp3 && id3v2tag != null) { foreach (CommentsFrame commentsframe in id3v2tag.GetFrames <CommentsFrame>()) { track.ID3Comments.Add(new Comment(commentsframe.Description, commentsframe.Language, commentsframe.Text)); } } else { track.Comment = file.Tag.Comment; } // Lyrics track.Lyrics = file.Tag.Lyrics; if (track.IsMp3 && id3v2tag != null) { foreach (UnsynchronisedLyricsFrame lyricsframe in id3v2tag.GetFrames <UnsynchronisedLyricsFrame>()) { // Only add non-empty Frames if (lyricsframe.Text != "") { track.LyricsFrames.Add(new Lyric(lyricsframe.Description, lyricsframe.Language, lyricsframe.Text)); } } } // Rating if (track.IsMp3) { TagLib.Id3v2.PopularimeterFrame popmFrame = null; // First read in all POPM Frames found if (id3v2tag != null) { foreach (PopularimeterFrame popmframe in id3v2tag.GetFrames <PopularimeterFrame>()) { // Only add valid POPM Frames if (popmframe.User != "" && popmframe.Rating > 0) { track.Ratings.Add(new PopmFrame(popmframe.User, (int)popmframe.Rating, (int)popmframe.PlayCount)); } } popmFrame = TagLib.Id3v2.PopularimeterFrame.Get(id3v2tag, "MPTagThat", false); if (popmFrame != null) { track.Rating = popmFrame.Rating; } } if (popmFrame == null) { // Now check for Ape Rating TagLib.Ape.Tag apetag = file.GetTag(TagTypes.Ape, true) as TagLib.Ape.Tag; TagLib.Ape.Item apeItem = apetag.GetItem("RATING"); if (apeItem != null) { string rating = apeItem.ToString(); try { track.Rating = Convert.ToInt32(rating); } catch (Exception) { } } } } else if (track.TagType == "ape") { TagLib.Ape.Tag apetag = file.GetTag(TagTypes.Ape, true) as TagLib.Ape.Tag; TagLib.Ape.Item apeItem = apetag.GetItem("RATING"); if (apeItem != null) { string rating = apeItem.ToString(); try { track.Rating = Convert.ToInt32(rating); } catch (Exception) { } } } else if (track.TagType == "ogg" || track.TagType == "flac") { XiphComment xiph = file.GetTag(TagLib.TagTypes.Xiph, false) as XiphComment; string[] rating = xiph.GetField("RATING"); if (rating.Length > 0) { try { track.Rating = Convert.ToInt32(rating[0]); } catch (Exception) { } } } } catch (Exception ex) { log.Error("Exception setting Tags for file: {0}. {1}", fileName, ex.Message); } #endregion #region Set Properties try { track.DurationTimespan = file.Properties.Duration; int fileLength = (int)(fi.Length / 1024); track.FileSize = fileLength.ToString(); track.BitRate = file.Properties.AudioBitrate.ToString(); track.SampleRate = file.Properties.AudioSampleRate.ToString(); track.Channels = file.Properties.AudioChannels.ToString(); track.Version = file.Properties.Description; track.CreationTime = string.Format("{0:yyyy-MM-dd HH:mm:ss}", fi.CreationTime); track.LastWriteTime = string.Format("{0:yyyy-MM-dd HH:mm:ss}", fi.LastWriteTime); } catch (Exception ex) { log.Error("Exception setting Properties for file: {0}. {1}", fileName, ex.Message); } #endregion // Now copy all Text frames of an ID3 V2 try { if (track.IsMp3 && id3v2tag != null) { foreach (TagLib.Id3v2.Frame frame in id3v2tag.GetFrames()) { string id = frame.FrameId.ToString(); if (!Util.StandardFrames.Contains(id) && Util.ExtendedFrames.Contains(id)) { track.Frames.Add(new Frame(id, "", frame.ToString())); } else if (!Util.StandardFrames.Contains(id) && !Util.ExtendedFrames.Contains(id)) { if ((Type)frame.GetType() == typeof(UserTextInformationFrame)) { // Don't add Replaygain frames, as they are handled in taglib tags if (!Util.IsReplayGain((frame as UserTextInformationFrame).Description)) { track.UserFrames.Add(new Frame(id, (frame as UserTextInformationFrame).Description ?? "", (frame as UserTextInformationFrame).Text.Length == 0 ? "" : (frame as UserTextInformationFrame).Text[0])); } } else if ((Type)frame.GetType() == typeof(PrivateFrame)) { track.UserFrames.Add(new Frame(id, (frame as PrivateFrame).Owner ?? "", (frame as PrivateFrame).PrivateData == null ? "" : (frame as PrivateFrame).PrivateData.ToString())); } else if ((Type)frame.GetType() == typeof(UniqueFileIdentifierFrame)) { track.UserFrames.Add(new Frame(id, (frame as UniqueFileIdentifierFrame).Owner ?? "", (frame as UniqueFileIdentifierFrame).Identifier == null ? "" : (frame as UniqueFileIdentifierFrame).Identifier.ToString())); } else if ((Type)frame.GetType() == typeof(UnknownFrame)) { track.UserFrames.Add(new Frame(id, "", (frame as UnknownFrame).Data == null ? "" : (frame as UnknownFrame).Data.ToString())); } else { track.UserFrames.Add(new Frame(id, "", frame.ToString())); } } } track.ID3Version = id3v2tag.Version; } } catch (Exception ex) { log.Error("Exception getting User Defined frames for file: {0}. {1}", fileName, ex.Message); } return(track); }
public static bool mp3_application(int m1, int m5, int m25, int m100, int m250, String nametag) { Console.WriteLine("1: ", m1); Console.WriteLine("5: ", m5); Console.WriteLine("25: ", m25); Console.WriteLine("100: ", m100); Console.WriteLine("250: ", m250); Console.WriteLine("String ", nametag); Encoding FileEncoding = Encoding.ASCII; //Define the encoding. TagLib.File Mp3File = null; // = TagLib.File.Create(Mp3Path); //Create TagLib file... ensures a Id3v2 header.; TagLib.Ape.Tag ApeTag = null; // = Mp3Methods.CheckApeTag(Mp3File); //return existing tag. create one if none. string[] collectCloudCoinStack = new string[3]; //State 1:endState[0] = MP3 filename //State 2:endState[1] = Name of external CloudCoinStack to be inserted. //State 3:endState[2] = Name of the CloudCoinStack currently found in the MP3. //State 4:endState[3] = //State 5:endState[4] = //State 6:endState[5] = string[] endState = new string[6]; //Keeps the current state of each case bool menuStyle = true; // Discriptive / Standard bool makingChanges = true; //Keeps the session runnning. string Mp3Path = null; Mp3Methods.printWelcome(); int userChoice = Mp3Methods.printOptions() + 1; Console.WriteLine(""); while (makingChanges) { switch (userChoice) { case 1: //Select .mp3 file. Mp3Path = Mp3Methods.ReturnMp3FilePath(); //Save file path. selectMp3(Mp3Path); break; case 2: //Select .stack file from Bank folder selectStack(); break; case 3: //Insert the .stack file into the .mp3 file stackToMp3(); break; case 4: //Return .stack from .mp3 stackFromMp3(); break; case 5: //Delete .stack from .mp3 deleteFromMp3(Mp3Path); break; case 6: //Save .mp3's current state saveMp3(); break; case 7: //Quit makingChanges = false; break; case 8: //Descriptions menuStyle = !menuStyle; break; default: Console.Out.WriteLine("No matches for input!"); break; } Console.Clear(); ///Switch bestween discriptive and standard menus options. switch (menuStyle) { case true: Mp3Methods.consoleGap(1); Mp3Methods.printStates(endState); userChoice = Mp3Methods.printOptions() + 1; break; case false: Mp3Methods.consoleGap(1); Mp3Methods.printStates(endState); userChoice = Mp3Methods.printHelp() + 1; break; } //end switch } //end while loop. Console.Out.WriteLine("Goodbye"); void selectMp3(string filePath) { if (filePath != "null") { Mp3File = TagLib.File.Create(filePath); //Create TagLib file... ensures a Id3v2 header. ApeTag = Mp3Methods.CheckApeTag(Mp3File); //return existing tag. create one if none. string fileName = Mp3File.Name; resetEndStates(fileName, ApeTag); endState[0] = "MP3 file: " + fileName + " has been selected. "; }// end if. else { endState[0] = "No file chosen."; } // end else. } // end selectMp3 void selectStack()//External souce to be inserted in the mp3 file. { try { collectCloudCoinStack = Mp3Methods.collectBankStacks(); //Select stacks to insert. if (collectCloudCoinStack[0] != "null") { endState[1] = "External Stack: " + collectCloudCoinStack[0]; } //end if else { endState[1] = "No stack file chose."; } //end else. } //end try catch { endState[1] = ".stack error "; } //end catch Console.Out.WriteLine(endState[1]); }// end selectStack void stackToMp3()//the process of inserting the selected stack into the file. { string cloudCoinStack = collectCloudCoinStack[1]; string stackName = collectCloudCoinStack[2]; Console.Out.WriteLine("Existing Stacks in the mp3 will be overwritten"); Console.Out.WriteLine("Enter/Return to continue, Any other key to go back."); if (Console.ReadKey(true).Key == ConsoleKey.Enter) //prompt user to continue. { if (cloudCoinStack != null && ApeTag != null) { Console.Out.WriteLine("Existing Stacks in the mp3 will be overwritten"); ApeTag = Mp3Methods.CheckApeTag(Mp3File); Mp3Methods.SetApeTagValue(ApeTag, cloudCoinStack, stackName); endState[2] = ".stack was successfully inserted in " + Mp3File.Name; endState[4] = "Stacks in " + Mp3File.Name + " have been added."; } //end if else { Mp3Methods.SetApeTagValue(ApeTag, cloudCoinStack, stackName); endState[2] = "No saved cloud coin stack."; } //end else Console.Out.WriteLine(endState[2]); } //end if }//end stackToMp3 void stackFromMp3()//returning the stack from the mp3 { Mp3File = TagLib.File.Create(Mp3Path); if (Mp3File != null) { string mp3CurrentCoinStack = Mp3Methods.ReturnCloudCoinStack(Mp3File); //The current stack from the mp3 gets saved. if (mp3CurrentCoinStack != "null") { endState[3] = "A file was created: " + mp3CurrentCoinStack; } //end if. else { endState[3] = "Incorrect key press."; } //end else. Console.Out.WriteLine(endState[3]); } //end if. else { Console.Out.WriteLine("No mp3 file selected."); } //end else. } //end stackFromMp3 void deleteFromMp3(string filePath) { Console.Out.WriteLine("WARNING: you are about to permenantley delete any stack files found in " + Mp3File.Name); Console.Out.WriteLine("Enter/Return to continue, Any other key to go back."); if (Console.ReadKey(true).Key == ConsoleKey.Enter) { bool isDeleted = Mp3Methods.RemoveExistingStacks(ApeTag); Console.Out.WriteLine(isDeleted); if (isDeleted) { Mp3File.Save(); selectMp3(filePath); // rerun code to update states. endState[4] = "Any existing stacks in " + Mp3File.Name + " have been deleted."; } //end if (is Deleted) else { endState[4] = "Stacks in " + Mp3File.Name + " have not been properly deleted."; } } //end if. else { endState[4] = "Stacks in " + Mp3File.Name + " have NOT been deleted."; } //end else. Console.Out.WriteLine(endState[4]); } // end deleteFromMp3. void saveMp3() { Mp3File.Save(); // Save changes. endState[5] = Mp3File.Name + " has been saved with the changes made"; Console.Out.WriteLine(endState[5]); }//end saveMp3 //Endstates are the 6 messages that are displayed to the user between actions. void resetEndStates(string filename, TagLib.Ape.Tag tag) { int length = endState.Length; TagLib.Ape.Item StackN = tag.GetItem("StackName"); //UPDATE endState[1]: remove current external cloudcoinstack. endState[1] = "No external CloudCoin stack selected."; for (int i = 0; i < 3; i++) { collectCloudCoinStack[i] = ""; }// end for //UPDATE endState[2]: Check for an existing CloudCoinStack in new file. if (StackN.Size <= 1) { endState[2] = filename + " does not include a stack."; }//end if else { Console.Out.WriteLine(StackN.Size); endState[2] = filename + " includes cloudcoin stack: " + StackN + "."; }// end else endState[3] = ""; endState[4] = ""; endState[5] = ""; } return(true); } //end Mp3Start.
void TagTestWithSave(ref Tag tag, TagTestFunc testFunc) { testFunc(tag, "Before Save"); tag = new Tag(tag.Render()); testFunc(tag, "After Save"); }
/// <summary> /// This method is called by mediaportal when it wants information for a music file /// The method will check which tagreader supports the file and ask it to extract the information from it /// </summary> /// <param name="strFile">filename of the music file</param> /// <returns> /// MusicTag instance when file has been read /// null when file type is not supported or if the file does not contain any information /// </returns> public static MusicTag ReadTag(string strFile) { // Read Cue info if (CueUtil.isCueFakeTrackFile(strFile)) { try { return(CueUtil.CueFakeTrackFile2MusicTag(strFile)); } catch (Exception ex) { Log.Warn("TagReader: Exception reading file {0}. {1}", strFile, ex.Message); } } if (!IsAudio(strFile)) { return(null); } char[] trimChars = { ' ', '\x00' }; try { // Set the flag to use the standard System Encoding set by the user // Otherwise Latin1 is used as default, which causes characters in various languages being displayed wrong TagLib.ByteVector.UseBrokenLatin1Behavior = true; TagLib.File tag = TagLib.File.Create(strFile); if (tag == null) { Log.Warn("Tagreader: No tag in file - {0}", strFile); return(null); } MusicTag musictag = new MusicTag(); string[] artists = tag.Tag.Performers; if (artists.Length > 0) { musictag.Artist = String.Join(";", artists).Trim(trimChars); // The AC/DC exception if (musictag.Artist.Contains("AC;DC")) { musictag.Artist = musictag.Artist.Replace("AC;DC", "AC/DC"); } } musictag.Album = tag.Tag.Album == null ? "" : tag.Tag.Album.Trim(trimChars); musictag.HasAlbumArtist = false; string[] albumartists = tag.Tag.AlbumArtists; if (albumartists.Length > 0) { musictag.AlbumArtist = String.Join(";", albumartists).Trim(trimChars); musictag.HasAlbumArtist = true; // The AC/DC exception if (musictag.AlbumArtist.Contains("AC;DC")) { musictag.AlbumArtist = musictag.AlbumArtist.Replace("AC;DC", "AC/DC"); } } musictag.BitRate = tag.Properties.AudioBitrate; musictag.Comment = tag.Tag.Comment == null ? "" : tag.Tag.Comment.Trim(trimChars); string[] composer = tag.Tag.Composers; if (composer.Length > 0) { musictag.Composer = string.Join(";", composer).Trim(trimChars); } musictag.Conductor = tag.Tag.Conductor == null ? "" : tag.Tag.Conductor.Trim(trimChars); IPicture[] pics = new IPicture[] { }; pics = tag.Tag.Pictures; if (pics.Length > 0) { musictag.CoverArtImageBytes = pics[0].Data.Data; } musictag.Duration = (int)tag.Properties.Duration.TotalSeconds; musictag.FileName = strFile; musictag.FileType = tag.MimeType.Substring(tag.MimeType.IndexOf("/") + 1); string[] genre = tag.Tag.Genres; if (genre.Length > 0) { musictag.Genre = String.Join(";", genre).Trim(trimChars); } string lyrics = tag.Tag.Lyrics == null ? "" : tag.Tag.Lyrics.Trim(trimChars); musictag.Title = tag.Tag.Title == null ? "" : tag.Tag.Title.Trim(trimChars); // Prevent Null Ref execption, when Title is not set musictag.Track = (int)tag.Tag.Track; musictag.TrackTotal = (int)tag.Tag.TrackCount; musictag.DiscID = (int)tag.Tag.Disc; musictag.DiscTotal = (int)tag.Tag.DiscCount; musictag.Codec = tag.Properties.Description; if (tag.MimeType == "taglib/mp3") { musictag.BitRateMode = tag.Properties.Description.IndexOf("VBR") > -1 ? "VBR" : "CBR"; } else { musictag.BitRateMode = ""; } musictag.BPM = (int)tag.Tag.BeatsPerMinute; musictag.Channels = tag.Properties.AudioChannels; musictag.SampleRate = tag.Properties.AudioSampleRate; musictag.Year = (int)tag.Tag.Year; musictag.ReplayGainTrack = tag.Tag.ReplayGainTrack ?? ""; musictag.ReplayGainTrackPeak = tag.Tag.ReplayGainTrackPeak ?? ""; musictag.ReplayGainAlbum = tag.Tag.ReplayGainAlbum ?? ""; musictag.ReplayGainAlbumPeak = tag.Tag.ReplayGainAlbumPeak ?? ""; if (tag.MimeType == "taglib/mp3") { bool foundPopm = false; // Handle the Rating, which comes from the POPM frame TagLib.Id3v2.Tag id32_tag = tag.GetTag(TagLib.TagTypes.Id3v2) as TagLib.Id3v2.Tag; if (id32_tag != null) { // Do we have a POPM frame written by MediaPortal or MPTagThat? TagLib.Id3v2.PopularimeterFrame popmFrame = TagLib.Id3v2.PopularimeterFrame.Get(id32_tag, "MediaPortal", false); if (popmFrame == null) { popmFrame = TagLib.Id3v2.PopularimeterFrame.Get(id32_tag, "MPTagThat", false); } if (popmFrame != null) { musictag.Rating = popmFrame.Rating; foundPopm = true; } // Now look for a POPM frame written by WMP if (!foundPopm) { TagLib.Id3v2.PopularimeterFrame popm = TagLib.Id3v2.PopularimeterFrame.Get(id32_tag, "Windows Media Player 9 Series", false); if (popm != null) { // Get the rating stored in the WMP POPM frame int rating = popm.Rating; int i = 0; if (rating == 255) { i = 5; } else if (rating == 196) { i = 4; } else if (rating == 128) { i = 3; } else if (rating == 64) { i = 2; } else if (rating == 1) { i = 1; } musictag.Rating = i; foundPopm = true; } } if (!foundPopm) { // Now look for any other POPM frame that might exist foreach (TagLib.Id3v2.PopularimeterFrame popm in id32_tag.GetFrames <TagLib.Id3v2.PopularimeterFrame>()) { int rating = popm.Rating; int i = 0; if (rating > 205 || rating == 5) { i = 5; } else if (rating > 154 || rating == 4) { i = 4; } else if (rating > 104 || rating == 3) { i = 3; } else if (rating > 53 || rating == 2) { i = 2; } else if (rating > 0 || rating == 1) { i = 1; } musictag.Rating = i; foundPopm = true; break; // we only take the first popm frame } } if (!foundPopm) { // If we don't have any POPM frame, we might have an APE Tag embedded in the mp3 file TagLib.Ape.Tag apetag = tag.GetTag(TagTypes.Ape, false) as TagLib.Ape.Tag; if (apetag != null) { TagLib.Ape.Item apeItem = apetag.GetItem("RATING"); if (apeItem != null) { string rating = apeItem.ToString(); try { musictag.Rating = Convert.ToInt32(rating); } catch (Exception ex) { musictag.Rating = 0; Log.Warn("Tagreader: Unsupported APE rating format - {0} in {1} {2}", rating, strFile, ex.Message); } } } } } } else { if (tag.MimeType == "taglib/ape") { TagLib.Ape.Tag apetag = tag.GetTag(TagTypes.Ape, false) as TagLib.Ape.Tag; if (apetag != null) { TagLib.Ape.Item apeItem = apetag.GetItem("RATING"); if (apeItem != null) { string rating = apeItem.ToString(); try { musictag.Rating = Convert.ToInt32(rating); } catch (Exception ex) { musictag.Rating = 0; Log.Warn("Tagreader: Unsupported APE rating format - {0} in {1} {2}", rating, strFile, ex.Message); } } } } } // if we didn't get a title, use the Filename without extension to prevent the file to appear as "unknown" if (musictag.Title == "") { Log.Warn("TagReader: Empty Title found in file: {0}. Please retag.", strFile); musictag.Title = System.IO.Path.GetFileNameWithoutExtension(strFile); } return(musictag); } catch (UnsupportedFormatException) { Log.Warn("Tagreader: Unsupported File Format {0}", strFile); } catch (Exception ex) { Log.Warn("TagReader: Exception reading file {0}. {1}", strFile, ex.Message); } return(null); }
/// <summary> /// Reads a tag starting at a specified position and moves the /// cursor to its start position. /// </summary> /// <param name="start"> /// A <see cref="long" /> value reference specifying at what /// position the potential tag starts. If a tag is found, /// this value will be updated to the position at which the /// found tag ends. /// </param> /// <returns> /// A <see cref="TagLib.Tag" /> object representing the tag /// found at the specified position, or <see langword="null" /// /> if no tag was found. /// </returns> private TagLib.Tag ReadTag (ref long start) { long end = start; TagTypes type = ReadTagInfo (ref end); TagLib.Tag tag = null; switch (type) { case TagTypes.Ape: tag = new TagLib.Ape.Tag (file, start); break; case TagTypes.Id3v2: tag = new TagLib.Id3v2.Tag (file, start); break; } start = end; return tag; }
/// <summary> /// Reads a tag ending at a specified position and moves the /// cursor to its start position. /// </summary> /// <param name="end"> /// A <see cref="long" /> value reference specifying at what /// position the potential tag ends at. If a tag is found, /// this value will be updated to the position at which the /// found tag starts. /// </param> /// <returns> /// A <see cref="TagLib.Tag" /> object representing the tag /// found at the specified position, or <see langword="null" /// /> if no tag was found. /// </returns> private TagLib.Tag ReadTag(ref long end) { long start = end; TagTypes type = ReadTagInfo (ref start); TagLib.Tag tag = null; try { switch (type) { case TagTypes.Ape: tag = new TagLib.Ape.Tag (file, end - TagLib.Ape.Footer.Size); break; case TagTypes.Id3v2: tag = new TagLib.Id3v2.Tag (file, start); break; case TagTypes.Id3v1: tag = new TagLib.Id3v1.Tag (file, start); break; } end = start; } catch (CorruptFileException) { } return tag; }
/// <summary> /// Adds a tag of a specified type to the current instance, /// optionally copying values from an existing type. /// </summary> /// <param name="type"> /// A <see cref="TagTypes" /> value specifying the type of /// tag to add to the current instance. At the time of this /// writing, this is limited to <see cref="TagTypes.Ape" />, /// <see cref="TagTypes.Id3v1" />, and <see /// cref="TagTypes.Id3v2" />. /// </param> /// <param name="copy"> /// A <see cref="TagLib.Tag" /> to copy values from using /// <see cref="TagLib.Tag.CopyTo" />, or <see /// langword="null" /> if no tag is to be copied. /// </param> /// <returns> /// The <see cref="TagLib.Tag" /> object added to the current /// instance, or <see langword="null" /> if it couldn't be /// created. /// </returns> /// <remarks> /// ID3v2 tags are added at the end of the current instance, /// while other tags are added to the beginning. /// </remarks> public TagLib.Tag AddTag(TagTypes type, TagLib.Tag copy) { TagLib.Tag tag = null; if (type == TagTypes.Id3v1) { tag = new TagLib.Id3v1.Tag (); } else if (type == TagTypes.Id3v2) { Id3v2.Tag tag32 = new Id3v2.Tag (); tag32.Version = 4; tag32.Flags |= Id3v2.HeaderFlags.FooterPresent; tag = tag32; } else if (type == TagTypes.Ape) { tag = new TagLib.Ape.Tag (); } if (tag != null) { if (copy != null) copy.CopyTo (tag, true); if (type == TagTypes.Id3v1) AddTag (tag); else InsertTag (0, tag); } return tag; }
/// <summary> /// Reads a tag starting at a specified position and moves the /// cursor to its start position. /// </summary> /// <param name="start"> /// A <see cref="long" /> value reference specifying at what /// position the potential tag starts. If a tag is found, /// this value will be updated to the position at which the /// found tag ends. /// </param> /// <returns> /// A <see cref="TagLib.Tag" /> object representing the tag /// found at the specified position, or <see langword="null" /// /> if no tag was found. /// </returns> private TagLib.Tag ReadTag(ref long start) { long end = start; TagTypes type = ReadTagInfo (ref end); TagLib.Tag tag = null; try { switch (type) { case TagTypes.Ape: tag = new TagLib.Ape.Tag (file, start); break; case TagTypes.Id3v2: tag = new TagLib.Id3v2.Tag (file, start); break; } } catch (CorruptFileException e) { Console.Error.WriteLine ("taglib-sharp caught exception creating tag: {0}", e); } start = end; return tag; }
/// <summary> /// Adds a tag of a specified type to the current instance, /// optionally copying values from an existing type. /// </summary> /// <param name="type"> /// A <see cref="TagTypes" /> value specifying the type of /// tag to add to the current instance. At the time of this /// writing, this is limited to <see cref="TagTypes.Ape" /> /// and <see cref="TagTypes.Id3v2" />. /// </param> /// <param name="copy"> /// A <see cref="TagLib.Tag" /> to copy values from using /// <see cref="TagLib.Tag.CopyTo" />, or <see /// langword="null" /> if no tag is to be copied. /// </param> /// <returns> /// The <see cref="TagLib.Tag" /> object added to the current /// instance, or <see langword="null" /> if it couldn't be /// created. /// </returns> /// <remarks> /// ID3v2 tags are added at the end of the current instance, /// while other tags are added to the beginning. /// </remarks> public TagLib.Tag AddTag(TagTypes type, TagLib.Tag copy) { TagLib.Tag tag = null; if (type == TagTypes.Id3v2) { tag = new TagLib.Id3v2.Tag (); } else if (type == TagTypes.Ape) { tag = new TagLib.Ape.Tag (); (tag as Ape.Tag).HeaderPresent = true; } if (tag != null) { if (copy != null) copy.CopyTo (tag, true); AddTag (tag); } return tag; }