Beispiel #1
0
        public Mp3Tagger(string path, bool write = true)
        {
            f = Utils.OpenFile(path, write);
            t = (TagLib.Id3v2.Tag)f.TagLibFile.GetTag(TagLib.TagTypes.Id3v2, true);
            if (t == null)
            {
                SafeClose();
                throw new HaException("MP3 file has no Id3v2 tag");
            }

            // ID3 is lame as hell, doesnt actually have textual description for tags (unlike beast-ass Xiph)
            valueTags.Add("album", FixString(t.Album));
            valueTags.Add("albumartist", FixString(Aggregate(t.AlbumArtists)));
            valueTags.Add("artist", FixString(Aggregate(t.Performers)));
            valueTags.Add("year", t.Year.ToString());

            IEnumerable <TagLib.Id3v2.UserTextInformationFrame> frames = t.GetFrames <TagLib.Id3v2.UserTextInformationFrame>().Where(x => x.Description.ToLower() == "hatag");

            if (frames.Count() > 0)
            {
                utif = frames.ElementAt(0);
                string data = utif.Text.Length == 0 ? "" : utif.Text[0];
                data.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList().ForEach(x => tags.Add(x));
            }
            else
            {
                utif = new TagLib.Id3v2.UserTextInformationFrame("hatag");
                utif.TextEncoding = TagLib.StringType.Latin1;
                t.AddFrame(utif);
            }
        }
        public static string GetTagContent(TagLib.Id3v2.Tag tag, string ID3v2Frame)
        {
            string tagContent = "";
            var    frames     = tag.GetFrames <TagLib.Id3v2.TextInformationFrame>(ID3v2Frame);

            foreach (TagLib.Id3v2.TextInformationFrame frame in frames)
            {
                foreach (string text in frame.Text)
                {
                    if (text.Length > tagContent.Length)
                    {
                        tagContent = text;
                    }
                }
            }

            return(tagContent);
        }
Beispiel #3
0
        // Overwrites all POPM frames with the new rating and playcount.
        // If no *known-compatible* frames are found, a new "Banshee"-authored
        // frame is also created to store this information.
        public static void StoreRatingAndPlayCount(int rating, int playcount,
                                                   TagLib.File to_file)
        {
            TagLib.Id3v2.Tag id3v2tag = GetTag(to_file);
            if (id3v2tag == null)
            {
                return;
            }

            bool known_frames_found = false;

            foreach (TagLib.Id3v2.PopularimeterFrame popm in
                     id3v2tag.GetFrames <TagLib.Id3v2.PopularimeterFrame> ())
            {
                if (System.Array.IndexOf(POPM_known_creator_list, popm.User) >= 0)
                {
                    // Found a known-good POPM frame, don't need to create a "Banshee" frame.
                    known_frames_found = true;
                }

                popm.Rating    = BansheeToPopm(rating);
                popm.PlayCount = (ulong)playcount;
                Hyena.Log.DebugFormat("Exporting ID3v2 Rating={0}({1}) and Playcount={2}({3}) to File \"{4}\" as Creator \"{5}\"",
                                      rating, popm.Rating,
                                      playcount, popm.PlayCount,
                                      to_file.Name, popm.User);
            }

            if (!known_frames_found)
            {
                // No known-good frames found, create a new POPM frame (with creator string "Banshee")
                TagLib.Id3v2.PopularimeterFrame popm = TagLib.Id3v2.PopularimeterFrame.Get(id3v2tag,
                                                                                           POPM_our_creator_name,
                                                                                           true);
                popm.Rating    = BansheeToPopm(rating);
                popm.PlayCount = (ulong)playcount;
                Hyena.Log.DebugFormat("Exporting ID3v2 Rating={0}({1}) and Playcount={2}({3}) to File \"{4}\" as Creator \"{5}\"",
                                      rating, popm.Rating,
                                      playcount, popm.PlayCount,
                                      to_file.Name, POPM_our_creator_name);
            }
        }
Beispiel #4
0
        /// <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);
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            var folderName = "C:\\Users\\Eric\\Music\\iTunes\\iTunes Music Library.xml";

            if (args.Count() > 0)
            {
                folderName = args[0];
            }

            var options = new ProgressBarOptions
            {
                ProgressCharacter   = '─',
                ProgressBarOnBottom = true
            };

            var library = new ITunesLibrary(folderName);

            // ignore streams (http://) for tracking
            var tracks = library.Tracks.Where(t => !t.Location.Contains("http://")).ToList();

            using (var pbar = new ProgressBar(tracks.Count(), "Initial message", options))
            {
                Parallel.ForEach(tracks, (itunesTrack) =>
                {
                    // create a windows path from the itunes location
                    var fileName = WebUtility.UrlDecode(itunesTrack.Location.Replace("+", "%2b")).Replace("file://localhost/", "").Replace("/", "\\");
                    try
                    {
                        TagLib.Id3v2.Tag.DefaultVersion      = 4;
                        TagLib.Id3v2.Tag.ForceDefaultVersion = true;

                        using (var mp3File = TagLib.File.Create(fileName))
                        {
                            TagLib.Id3v2.Tag tag = (TagLib.Id3v2.Tag)mp3File.GetTag(TagLib.TagTypes.Id3v2, true);

                            // strip old popularity frames
                            foreach (var oldPopFrame in tag.GetFrames <TagLib.Id3v2.PopularimeterFrame>().ToArray())
                            {
                                tag.RemoveFrame(oldPopFrame);
                            }

                            //tag.AlbumArtists = new[] { itunesTrack.AlbumArtist };
                            //tag.Performers = new[] { itunesTrack.Artist };
                            //tag.Genres = new[] { itunesTrack.Genre };
                            //tag.IsCompilation = itunesTrack.PartOfCompilation;

                            //RemoveLyrics(mp3File);

                            var frame = TagLib.Id3v2.PopularimeterFrame.Get(tag, "Windows Media Player 9 Series", true);
                            if (itunesTrack.Rating.HasValue)
                            {
                                var stars    = itunesTrack.Rating.Value / 20; // itunes sends 20 x star value
                                frame.Rating = TransformRating(stars);
                            }
                            if (itunesTrack.PlayCount.HasValue && (ulong)itunesTrack.PlayCount.Value > frame.PlayCount)
                            {
                                frame.PlayCount = (ulong)itunesTrack.PlayCount.Value;
                            }

                            //only keep existing tags in file
                            var removeTags = mp3File.TagTypes & ~mp3File.TagTypesOnDisk;
                            mp3File.RemoveTags(removeTags);
                            mp3File.Save();
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Error updating the playcount: {ex.Message}");
                    }

                    pbar.Tick($"updating {fileName}");
                });
            }
        }
Beispiel #6
0
        /// <summary>
        /// Liest aus dem Übergebenen Pfad die Metadaten des Songs aus
        /// </summary>
        /// <param name="pfad">Ort wo die Datei liegt</param>
        /// <returns>Das entsprechende MP3File Objekt</returns>
        public static MP3File ReadMetaData(string pfad)
        {
            MP3File lied = new MP3File();

            try
            {
                lied.Pfad = pfad;
                //Taglib Objekt erstellen
                //Wenn die Datei existiert verarbeiten.
                if (File.Exists(lied.Pfad))
                {
                    TagLib.File taglibobjekt = TagLib.File.Create(lied.Pfad);

                    if (taglibobjekt.Tag.Lyrics != null)
                    {
                        string dummy = Regex.Replace(taglibobjekt.Tag.Lyrics, @"[\r\n]+", "<br />");
                        dummy      = Regex.Replace(dummy, "Deutsch:", "<b>Deutsch:</b>");
                        lied.Lyric = Regex.Replace(dummy, "Englisch:", "<b>Englisch:</b>");
                    }
                    else
                    {
                        lied.Lyric = MP3Lyrics.NoLyrics.ToString();
                    }
                    //Global
                    lied.Typ       = taglibobjekt.MimeType;
                    lied.Genre     = (taglibobjekt.Tag.Genres != null && taglibobjekt.Tag.Genres.Length > 0 ? taglibobjekt.Tag.Genres[0] : "leer");
                    lied.Laufzeit  = taglibobjekt.Properties.Duration;
                    lied.Kommentar = taglibobjekt.Tag.Comment;
                    //Cover
                    if (taglibobjekt.Tag.Pictures.Length == 0)
                    {
                        lied.HatCover = false;
                    }
                    if (!String.IsNullOrEmpty(taglibobjekt.Tag.Publisher))
                    {
                        lied.Verlag = taglibobjekt.Tag.Publisher;
                    }
                    if (!String.IsNullOrEmpty(taglibobjekt.Tag.FirstComposer))
                    {
                        lied.Komponist = taglibobjekt.Tag.FirstComposer;
                    }
                    string art = "";
                    switch (taglibobjekt.MimeType)
                    {
                    case "taglib/flac":
                    case "taglib/m4a":
                        lied.Album = taglibobjekt.Tag.Album;
                        if (!String.IsNullOrEmpty(taglibobjekt.Tag.FirstPerformer))
                        {
                            art = taglibobjekt.Tag.FirstPerformer;
                        }
                        if (!String.IsNullOrEmpty(taglibobjekt.Tag.FirstAlbumArtist))
                        {
                            art = taglibobjekt.Tag.FirstAlbumArtist;
                        }
                        lied.Artist = art;
                        if (taglibobjekt.Tag.Rating != null && taglibobjekt.Tag.Rating != "Not Set")
                        {
                            int r;
                            int.TryParse(taglibobjekt.Tag.Rating, out r);
                            lied.Bewertung = taglibobjekt.Tag.Rating;
                            //Flac wird von MM eine Bome gleich 0 gesetzt Für die Verarbeitung von allen anderen Dingen wird hier das Verarbeiten
                            //Wie bei MP3 auf -1 gesetzt.
                            if (r == 0)
                            {
                                lied.Bewertung = "-1";
                            }
                        }
                        else
                        {
                            lied.Bewertung = "0";
                        }
                        Enums.Gelegenheit lge = Enums.Gelegenheit.None;
                        if (!string.IsNullOrEmpty(taglibobjekt.Tag.Occasion))
                        {
                            Enum.TryParse(taglibobjekt.Tag.Occasion, false, out lge);
                        }
                        lied.Gelegenheit = lge;
                        Enums.Geschwindigkeit lg = Enums.Geschwindigkeit.None;
                        if (!string.IsNullOrEmpty(taglibobjekt.Tag.Tempo))
                        {
                            Enum.TryParse(taglibobjekt.Tag.Tempo.Replace(" ", "_"), false, out lg);
                        }
                        lied.Geschwindigkeit = lg;
                        lied.Jahr            = taglibobjekt.Tag.Year.ToString();
                        if (string.IsNullOrEmpty(taglibobjekt.Tag.Mood))
                        {
                            lied.Stimmung = Enums.Stimmung.None;
                        }
                        else
                        {
                            Enums.Stimmung ls;
                            Enum.TryParse(taglibobjekt.Tag.Mood, false, out ls);
                            lied.Stimmung = ls;
                        }
                        lied.Titel          = taglibobjekt.Tag.Title;
                        lied.Aufwecken      = !String.IsNullOrEmpty(taglibobjekt.Tag.MMCustom2);
                        lied.ArtistPlaylist = !String.IsNullOrEmpty(taglibobjekt.Tag.MMCustom3);
                        lied.BewertungMine  = taglibobjekt.Tag.MMCustom1 ?? "0";

                        break;

                    case "taglib/mp3":
                        #region mp3

                        TagLib.Id3v2.Tag id3v2tag = taglibobjekt.GetTag(TagLib.TagTypes.Id3v2) as TagLib.Id3v2.Tag;
                        if (id3v2tag != null)
                        {
                            lied.Album = id3v2tag.Album;
                            art        = "";
                            if (!String.IsNullOrEmpty(id3v2tag.FirstPerformer))
                            {
                                art = taglibobjekt.Tag.FirstPerformer;
                            }
                            if (!String.IsNullOrEmpty(id3v2tag.FirstAlbumArtist))
                            {
                                art = taglibobjekt.Tag.FirstAlbumArtist;
                            }
                            lied.Artist    = art;
                            lied.Jahr      = id3v2tag.Year.ToString();
                            lied.Komponist = id3v2tag.FirstComposer;
                            lied.Titel     = id3v2tag.Title;
                            #region Rating
                            TagLib.Id3v2.PopularimeterFrame popm = TagLib.Id3v2.PopularimeterFrame.Get(id3v2tag, "no@email", false);
                            if (popm != null)
                            {
                                int songratingstring = Convert.ToInt16(popm.Rating);
                                int resultval        = -1; //Bombe
                                if (songratingstring > 8 && songratingstring < 40)
                                {
                                    resultval = 10;    //0,5
                                }
                                if ((songratingstring > 39 && songratingstring < 50) || songratingstring == 1)
                                {
                                    resultval = 20;    //1
                                }
                                if (songratingstring > 49 && songratingstring < 60)
                                {
                                    resultval = 30;    //1,5
                                }
                                if (songratingstring > 59 && songratingstring < 114)
                                {
                                    resultval = 40;    //2
                                }
                                if (songratingstring > 113 && songratingstring < 125)
                                {
                                    resultval = 50;    //2,5
                                }
                                if (songratingstring > 124 && songratingstring < 168)
                                {
                                    resultval = 60;    //3
                                }
                                if (songratingstring > 167 && songratingstring < 192)
                                {
                                    resultval = 70;    //3,5
                                }
                                if (songratingstring > 191 && songratingstring < 219)
                                {
                                    resultval = 80;    //4
                                }
                                if (songratingstring > 218 && songratingstring < 248)
                                {
                                    resultval = 90;    //4,5
                                }
                                if (songratingstring > 247)
                                {
                                    resultval = 100;    //5
                                }
                                lied.Bewertung = resultval.ToString();
                            }
                            else
                            {
                                lied.Bewertung = "0";
                            }
                            #endregion Rating
                            //Gelegenheiten und Custom MM DB auslesen auslesen.
                            #region Gelegenheiten
                            IEnumerable <TagLib.Id3v2.Frame> comm = id3v2tag.GetFrames("COMM");
                            Enums.Gelegenheit     gelegenheit     = Enums.Gelegenheit.None;
                            Enums.Geschwindigkeit geschwindigkeit = Enums.Geschwindigkeit.None;
                            Enums.Stimmung        stimmung        = Enums.Stimmung.None;
                            Boolean aufwecken      = false;
                            String  ratingmine     = "0";
                            Boolean artistplaylist = false;
                            foreach (var b in comm)
                            {
                                if (((TagLib.Id3v2.CommentsFrame)b).Description == "MusicMatch_Situation")
                                {
                                    string t = ((TagLib.Id3v2.CommentsFrame)b).Text;
                                    if (!string.IsNullOrEmpty(t))
                                    {
                                        Enum.TryParse(t, false, out gelegenheit);
                                    }
                                }
                                if (((TagLib.Id3v2.CommentsFrame)b).Description == "MusicMatch_Tempo")
                                {
                                    var k = ((TagLib.Id3v2.CommentsFrame)b).Text.Replace(" ", "_");
                                    if (!string.IsNullOrEmpty(k))
                                    {
                                        Enum.TryParse(k, false, out geschwindigkeit);
                                    }
                                }
                                if (((TagLib.Id3v2.CommentsFrame)b).Description == "MusicMatch_Mood")
                                {
                                    var x = ((TagLib.Id3v2.CommentsFrame)b).Text;
                                    if (!string.IsNullOrEmpty(x))
                                    {
                                        Enum.TryParse(x, false, out stimmung);
                                    }
                                }
                                //aufwecken
                                if (((TagLib.Id3v2.CommentsFrame)b).Description == "Songs-DB_Custom2")
                                {
                                    aufwecken = !String.IsNullOrEmpty(((TagLib.Id3v2.CommentsFrame)b).Text);
                                }
                                //Rating Mine
                                if (((TagLib.Id3v2.CommentsFrame)b).Description == "Songs-DB_Custom1")
                                {
                                    ratingmine = String.IsNullOrEmpty(((TagLib.Id3v2.CommentsFrame)b).Text) ? "0" : ((TagLib.Id3v2.CommentsFrame)b).Text;
                                }
                                //ArtistPlaylist
                                if (((TagLib.Id3v2.CommentsFrame)b).Description == "Songs-DB_Custom3")
                                {
                                    artistplaylist = !String.IsNullOrEmpty(((TagLib.Id3v2.CommentsFrame)b).Text);
                                }
                            }
                            lied.Gelegenheit     = gelegenheit;
                            lied.Geschwindigkeit = geschwindigkeit;
                            lied.Stimmung        = stimmung;
                            lied.Aufwecken       = aufwecken;
                            lied.ArtistPlaylist  = artistplaylist;
                            #endregion Gelegenheiten
                            lied.BewertungMine = ratingmine;
                        }
                        #endregion mp3
                        break;
                    }//Ende Switch für die MIMETypes

                    taglibobjekt.Dispose();
                    return(lied);
                }
                //Songpfad existiert nicht
                lied.VerarbeitungsFehler = true;
                return(lied);
            }
            catch
            {
                lied.VerarbeitungsFehler = true;
                return(lied);
            }
        }
Beispiel #7
0
        /// <summary>
        /// Schreibt die Metadata des übergebenen Songs
        /// </summary>
        /// <param name="song"></param>
        /// <returns></returns>
        public static Boolean WriteMetaData(MP3File song)
        {
            String orgrating = String.Empty;

            try
            {
                //Taglib Objekt erstellen
                TagLib.File taglibobjekt = TagLib.File.Create(song.Pfad);
                //taglibobjekt.Tag.Genres[0] = song.Genre;
                switch (taglibobjekt.MimeType)
                {
                case "taglib/flac":
                case "taglib/m4a":
                    if (song.Bewertung != "No")
                    {
                        //MM Behandelt Bomben bei FLAc anders als bei MP3
                        //Beim setzten wird hier nun -1 auf 0 gesetzt und 0 als nicht vorhanden.
                        orgrating = song.Bewertung;     //Für ein Catch den alten wert merken.
                        if (song.Bewertung == "0")
                        {
                            song.Bewertung = "";
                        }
                        if (song.Bewertung == "-1")
                        {
                            song.Bewertung = "0";
                        }
                        taglibobjekt.Tag.Rating = song.Bewertung;
                    }
                    taglibobjekt.Tag.Mood      = song.Stimmung.ToString();
                    taglibobjekt.Tag.Occasion  = song.Gelegenheit.ToString();
                    taglibobjekt.Tag.Tempo     = song.Geschwindigkeit.ToString().Replace("_", " ");
                    taglibobjekt.Tag.MMCustom1 = song.BewertungMine;
                    taglibobjekt.Tag.MMCustom2 = (song.Aufwecken) ? "Aufwecken" : String.Empty;
                    taglibobjekt.Tag.MMCustom3 = (song.ArtistPlaylist) ? "true" : String.Empty;
                    break;

                case "taglib/mp3":
                    TagLib.Id3v2.Tag id3v2tag = taglibobjekt.GetTag(TagLib.TagTypes.Id3v2) as TagLib.Id3v2.Tag;
                    #region Rating
                    if (song.Bewertung != "No")
                    {
                        TagLib.Id3v2.PopularimeterFrame popm = TagLib.Id3v2.PopularimeterFrame.Get(id3v2tag, "no@email", true);
                        //Das Rating wurde entfernt oder gesetzt
                        if (song.Bewertung == "0")
                        {
                            if (id3v2tag != null)
                            {
                                id3v2tag.RemoveFrame(popm);
                            }
                        }
                        else
                        {
                            int ratingval = 0;          //Bombe
                            if (song.Bewertung == "10") //0,5
                            {
                                ratingval = 30;
                            }
                            if (song.Bewertung == "20")    //1
                            {
                                ratingval = 45;
                            }
                            if (song.Bewertung == "30")    //1,5
                            {
                                ratingval = 55;
                            }
                            if (song.Bewertung == "40")    //2
                            {
                                ratingval = 100;
                            }
                            if (song.Bewertung == "50")    //2,5
                            {
                                ratingval = 120;
                            }
                            if (song.Bewertung == "60")    //3
                            {
                                ratingval = 153;
                            }
                            if (song.Bewertung == "70")    //3,5
                            {
                                ratingval = 180;
                            }
                            if (song.Bewertung == "80")    //4
                            {
                                ratingval = 202;
                            }
                            if (song.Bewertung == "90")    //4,5
                            {
                                ratingval = 245;
                            }
                            if (song.Bewertung == "100")    //5
                            {
                                ratingval = 253;
                            }

                            popm.Rating = Convert.ToByte(ratingval);
                        }
                    }

                    #endregion Rating
                    #region Gelegenenheiten
                    /*Ermitteln und ändern falls vorhanden. Andernfalls neu generien*/
                    if (id3v2tag != null)
                    {
                        IEnumerable <TagLib.Id3v2.Frame> comm = id3v2tag.GetFrames("COMM");
                        Boolean setgelegenheit     = false;
                        Boolean setgeschwindigkeit = false;
                        Boolean setstimmung        = false;
                        Boolean aufwecken          = false;
                        Boolean artisplaylist      = false;
                        Boolean setratingMine      = false;
                        // Boolean ratingmine = false;
                        foreach (var b in comm)
                        {
                            string des = ((TagLib.Id3v2.CommentsFrame)b).Description;

                            switch (des)
                            {
                            case "MusicMatch_Situation":
                            case "Songs-DB_Occasion":
                                ((TagLib.Id3v2.CommentsFrame)b).Text = song.Gelegenheit.ToString();
                                setgelegenheit = true;
                                break;

                            case "MusicMatch_Tempo":
                            case "Songs-DB_Tempo":
                                ((TagLib.Id3v2.CommentsFrame)b).Text = song.Geschwindigkeit.ToString().Replace("_", " ");
                                setgeschwindigkeit = true;
                                break;

                            case "MusicMatch_Mood":
                            case "Songs-DB_Mood":
                                ((TagLib.Id3v2.CommentsFrame)b).Text = song.Stimmung.ToString();
                                setstimmung = true;
                                break;

                            case "Songs-DB_Custom2":
                                ((TagLib.Id3v2.CommentsFrame)b).Text = song.Aufwecken ? "Aufwecken" : "";
                                aufwecken = true;

                                break;

                            case "Songs-DB_Custom3":
                                ((TagLib.Id3v2.CommentsFrame)b).Text = song.ArtistPlaylist ? "true" : "";
                                artisplaylist = true;

                                break;

                            case "Songs-DB_Custom1":
                                ((TagLib.Id3v2.CommentsFrame)b).Text = song.BewertungMine;
                                setratingMine = true;
                                break;
                            }
                        }    //Ende foreach
                        if (!aufwecken && song.Aufwecken)
                        {
                            TagLib.Id3v2.CommentsFrame mms = new TagLib.Id3v2.CommentsFrame("Songs-DB_Custom2", "xxx")
                            {
                                Text = "Aufwecken"
                            };
                            id3v2tag.AddFrame(mms);
                        }
                        if (!artisplaylist && song.ArtistPlaylist)
                        {
                            TagLib.Id3v2.CommentsFrame mms = new TagLib.Id3v2.CommentsFrame("Songs-DB_Custom3", "xxx")
                            {
                                Text = "true"
                            };
                            id3v2tag.AddFrame(mms);
                        }
                        if (!setratingMine)
                        {
                            TagLib.Id3v2.CommentsFrame mms = new TagLib.Id3v2.CommentsFrame("Songs-DB_Custom1", "xxx")
                            {
                                Text = song.BewertungMine
                            };
                            id3v2tag.AddFrame(mms);
                        }
                        if (!setgelegenheit)
                        {
                            TagLib.Id3v2.CommentsFrame mms = new TagLib.Id3v2.CommentsFrame("MusicMatch_Situation", "xxx");
                            TagLib.Id3v2.CommentsFrame sdo = new TagLib.Id3v2.CommentsFrame("Songs-DB_Occasion", "xxx");
                            mms.Text = song.Gelegenheit.ToString();
                            sdo.Text = song.Gelegenheit.ToString();
                            id3v2tag.AddFrame(mms);
                            id3v2tag.AddFrame(sdo);
                        }
                        if (!setgeschwindigkeit)
                        {
                            TagLib.Id3v2.CommentsFrame mms = new TagLib.Id3v2.CommentsFrame("MusicMatch_Tempo", "xxx");
                            TagLib.Id3v2.CommentsFrame sdo = new TagLib.Id3v2.CommentsFrame("Songs-DB_Tempo", "xxx");
                            mms.Text = song.Geschwindigkeit.ToString().Replace("_", " ");
                            sdo.Text = song.Geschwindigkeit.ToString().Replace("_", " ");
                            id3v2tag.AddFrame(mms);
                            id3v2tag.AddFrame(sdo);
                        }
                        if (!setstimmung)
                        {
                            TagLib.Id3v2.CommentsFrame mms = new TagLib.Id3v2.CommentsFrame("MusicMatch_Mood", "xxx");
                            TagLib.Id3v2.CommentsFrame sdo = new TagLib.Id3v2.CommentsFrame("Songs-DB_Mood", "xxx");
                            mms.Text = song.Stimmung.ToString();
                            sdo.Text = song.Stimmung.ToString();
                            id3v2tag.AddFrame(mms);
                            id3v2tag.AddFrame(sdo);
                        }
                    }

                    #endregion Gelegenheiten
                    break;
                }


                taglibobjekt.Save();
                taglibobjekt.Dispose();

                //For Debuging

                /*
                 * StringBuilder sb = new StringBuilder();
                 * sb.AppendLine("Update Done");
                 * sb.AppendLine(lied.Pfad);
                 * sb.AppendLine(lied.Bewertung);
                 * using (StreamWriter outfile = new StreamWriter(@"C:\done.txt"))
                 * {
                 *  outfile.Write(sb.ToString());
                 *
                 * }
                 */
                return(true);
            }
            catch
            {
                if (!String.IsNullOrEmpty(orgrating))
                {
                    song.Bewertung = orgrating; //OriginaleBewertung wieder herstellen.
                }
                return(false);
            }
        }