Ejemplo n.º 1
0
        /// <summary>
        /// Retrieve a tag with an arbitrary name.
        /// Returns an empty tag if the value isn't found or if no Xiph tags are present.
        /// </summary>
        /// <param name="TagName">
        /// A <see cref="System.String"/> containing the name of the tag to find
        /// </param>
        /// <returns>
        /// An <see cref="OggTag"/> containing the returned tag
        /// </returns>
        public OggTag GetTag(string TagName)
        {
            if (TagName.Length <= 0)
            {
                return(OggUtilities.GetEmptyTag());
            }                                                                         // Save some processing time and just exit if we haven't been given a tag name
            // Based on tasty examples @ "Accessing Hidden Gems": http://developer.novell.com/wiki/index.php/TagLib_Sharp:_Examples
            XiphComment XC = (XiphComment)m_TagLibFile.GetTag(TagTypes.Xiph);

            if (XC != null)
            {
                string[] TagValue = XC.GetField(TagName);
                if (TagValue.Length == 0)
                {
                    // Tag doesn't exist, return empty
                    return(OggUtilities.GetEmptyTag());
                }
                else
                {
                    OggTag tmpTag;
                    tmpTag.Name    = TagName;
                    tmpTag.IsArray = (TagValue.Length > 1);
                    tmpTag.IsEmpty = false;
                    tmpTag.Values  = TagValue;
                    tmpTag.Value   = TagValue[0];
                    return(tmpTag);
                }
            }
            else
            {
                // No valid Xiph tags found
                return(OggUtilities.GetEmptyTag());
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Retrieve an array of all tag values
        /// Returns a zero-length array if no Xiph tags are found
        /// </summary>
        /// <returns>
        /// An <see cref="OggTag[]"/> containing the returned values
        /// </returns>
        public OggTag[] GetTags()
        {
            XiphComment XC = (XiphComment)m_TagLibFile.GetTag(TagTypes.Xiph);

            if (XC != null)
            {
                if (XC.FieldCount > 0)
                {
                    OggTag[] tmpOggTag = new OggTag[XC.FieldCount];
                    int      Index     = 0;
                    foreach (string FieldName in XC)
                    {
                        string[] TagValue = XC.GetField(FieldName);
                        if (TagValue.Length == 0)
                        {
                            tmpOggTag[Index] = OggUtilities.GetEmptyTag();                                      // This should never happen, but I bet if I don't check it it will!
                        }
                        else
                        {
                            // Populate this tag
                            tmpOggTag[Index].Name    = FieldName;
                            tmpOggTag[Index].IsArray = (TagValue.Length > 1);
                            tmpOggTag[Index].IsEmpty = false;
                            tmpOggTag[Index].Values  = TagValue;
                            tmpOggTag[Index].Value   = TagValue[0];
                        }
                        ++Index;                                // Increment the index so we know which OggTag we're molesting
                    }
                    // Done! Return the heap of tags
                    return(tmpOggTag);
                }
                else
                {
                    // Xiph tags contain no items
                    return(new OggTag[0]);
                }
            }
            else
            {
                // No valid Xiph tags found
                return(new OggTag[0]);
            }
        }
Ejemplo n.º 3
0
        /// <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);
        }