// Scans the file for *known-compatible* POPM frames, with priority given to // frames at the top of the known creator list. public static void GetRatingAndPlayCount(TagLib.File from_file, ref int rating, ref int playcount) { TagLib.Id3v2.Tag id3v2tag = GetTag(from_file); if (id3v2tag == null) { return; } TagLib.Id3v2.PopularimeterFrame popm = null; for (int i = 0; i < POPM_known_creator_list.Length; i++) { popm = TagLib.Id3v2.PopularimeterFrame.Get(id3v2tag, POPM_known_creator_list[i], false); if (popm != null) { break; } } if (popm != null) { rating = PopmToBanshee(popm.Rating); playcount = (int)popm.PlayCount; } }
public int GetRating(string path) { TagLib.File fi = TagLib.File.Create(path); TagLib.Tag tag = fi.GetTag(TagLib.TagTypes.Id3v2); TagLib.Id3v2.PopularimeterFrame popM = TagLib.Id3v2.PopularimeterFrame.Get((TagLib.Id3v2.Tag)tag, Defaults.PopMUser, true); return(PopM2StarRating(popM.Rating)); }
// 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); } }
/// <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); }
public static void WriteMP3Tags(SoundFileInformation sfi, Field field) { // Im Moment nur MP3 string ext = Path.GetExtension(sfi.Filename).ToLower(); if (ext != ".mp3" && ext != ".flac" && ext != ".wma" && ext != ".ogg") { return; } using (TagLib.File tagFile = TagLib.File.Create(sfi.Filename)) { int id3Version = Settings.Current.UseID3Version; switch (field) { case Field.ArtistTrackName: { tagFile.Tag.Performers = new string[] { sfi.Artist }; break; } case Field.Title: { tagFile.Tag.Album = sfi.Album; break; } case Field.TrackNumber: { tagFile.Tag.Track = (uint)sfi.TrackNumber; } break; case Field.TrackCategory: { tagFile.Tag.Genres = new string[] { sfi.Genre }; break; } case Field.ArtistCDName: { tagFile.Tag.AlbumArtists = new string[] { sfi.AlbumArtist }; break; } case Field.ComposerTrackName: { tagFile.Tag.Composers = new string[] { sfi.Composer }; break; } case Field.TrackTitle: { tagFile.Tag.Title = sfi.Title; break; } case Field.TrackYearRecorded: { tagFile.Tag.Year = (uint)sfi.Year; break; } case Field.TrackComment: { tagFile.Tag.Comment = sfi.Comment; break; } case Field.TrackRating: { if (sfi.Rating > 0 && ext == ".mp3") { TagLib.Id3v2.PopularimeterFrame popFrame = TagLib.Id3v2.PopularimeterFrame.Get((TagLib.Id3v2.Tag)tagFile.GetTag(TagLib.TagTypes.Id3v2), "*****@*****.**", true); popFrame.User = "******"; popFrame.Rating = (byte)sfi.Rating; popFrame.PlayCount = (ulong)sfi.PlayCount; } break; } case Field.TrackPlayCount: { /*id3Info.ID3v2Info.PlayCounter = new ID3.ID3v2Frames.OtherFrames.PlayCounterFrame((FrameFlags)0); * * id3Info.ID3v2Info.PlayCounter.Counter = sfi.PlayCount;*/ break; } } tagFile.Save(); } }
public static void WriteMP3Tags(string filename, CD cd, int track) { // Im Moment nur MP3 string ext = Path.GetExtension(filename).ToLower(); if (ext != ".mp3" && ext != ".flac" && ext != ".wma" && ext != ".ogg") { return; } using (TagLib.File tagFile = TagLib.File.Create(filename)) { int id3Version = Settings.Current.UseID3Version; int year = cd.Tracks[track].YearRecorded != 0 ? cd.Tracks[track].YearRecorded : cd.YearRecorded; string category = !String.IsNullOrEmpty(cd.Tracks[track].Category) ? cd.Tracks[track].Category : cd.Category; string language = !String.IsNullOrEmpty(cd.Tracks[track].Language) ? cd.Tracks[track].Language : cd.Language; tagFile.Tag.Performers = new string[] { cd.Tracks[track].Artist }; tagFile.Tag.AlbumArtists = new string[] { cd.Artist }; tagFile.Tag.Title = cd.Tracks[track].Title; tagFile.Tag.Comment = cd.Tracks[track].Comment; tagFile.Tag.Track = (uint)cd.Tracks[track].TrackNumber; tagFile.Tag.Album = cd.Title; tagFile.Tag.Year = (uint)year; if (category != null) { tagFile.Tag.Genres = new string[] { category } } ; tagFile.Tag.Composers = new string[] { cd.Tracks[track].Composer }; //TODO!!!!!!!!!!!!!id3Info.ID3v2Info.SetTextFrame("TLAN", language); if (cd.CDSetNumber > 0) { tagFile.Tag.Disc = (uint)cd.CDSetNumber; } //TODO!!!!!!!!id3Info.ID3v2Info.SetTextFrame("PCNT", cd.Tracks[track].PlayCount.ToString()); // Rating ist eine Liste von Einträgen. Wir suchen hier nach dem Eintrag "*****@*****.**". if (cd.Tracks[track].Rating > 0 && ext == ".mp3") { TagLib.Id3v2.PopularimeterFrame popFrame = TagLib.Id3v2.PopularimeterFrame.Get((TagLib.Id3v2.Tag)tagFile.GetTag(TagLib.TagTypes.Id3v2), "*****@*****.**", true); popFrame.User = "******"; popFrame.Rating = (byte)cd.Tracks[track].Rating; popFrame.PlayCount = (ulong)cd.Tracks[track].PlayCount; } tagFile.Tag.BeatsPerMinute = (uint)cd.Tracks[track].Bpm; //TODO!!!!!!!!!!!!!tagFile.Tag.id3Info.ID3v2Info.SetTextFrame("TLEN", cd.Tracks[track].Length > 0 ? cd.Tracks[track].Length.ToString() : ""); try { if (!string.IsNullOrEmpty(cd.CDCoverFrontFilename)) { byte[] filefrontcover = File.ReadAllBytes(Misc.FindCover(cd.CDCoverFrontFilename)); string mimetype; mimetype = GetMIMEType(Path.GetExtension(cd.CDCoverFrontFilename)); MemoryStream memstream = new MemoryStream(filefrontcover); TagLib.Picture pict = new TagLib.Picture(); pict.MimeType = mimetype; pict.Data = memstream.ToArray(); pict.Type = TagLib.PictureType.FrontCover; tagFile.Tag.Pictures = new TagLib.IPicture[] { pict }; } } catch { // Pech gehabt - kein Cover } tagFile.Tag.Lyrics = cd.Tracks[track].Lyrics; try { tagFile.Save(); } catch (Exception e) { System.Windows.Application.Current.Dispatcher.Invoke( new Action(delegate { WPFMessageBox msgBox = new WPFMessageBox(); msgBox.HeaderText = StringTable.WriteID3TagsAccessDeniedTitle; msgBox.Text = string.Format(StringTable.WriteID3TagsAccessDenied, filename); msgBox.Image = "/Big3.Hitbase.SharedResources;component/Images/Info.png"; msgBox.Owner = System.Windows.Application.Current.MainWindow; msgBox.WpfMessageBoxButtons = WpfMessageBoxButtons.OK; msgBox.ZoomImage = false; msgBox.Width = 600; msgBox.Height = 400; msgBox.ShowInTaskbar = false; msgBox.DontShowAgainText = StringTable.DontDisplayAgain; msgBox.SaveAnswer = true; msgBox.SaveAnswerInRegistryKey = "ID3RenameAccessDenied"; msgBox.ShowDialogEventually(); })); } } }
public static void GetSoundFileInformation(SoundFileInformation soundFileInfo, string filename) { soundFileInfo.Filename = filename; try { if (string.IsNullOrEmpty(filename) || !System.IO.File.Exists(filename)) { return; } string ext = Path.GetExtension(filename).ToLower(); using (TagLib.File tagFile = TagLib.File.Create(filename)) { if (tagFile.Tag.Performers.Length > 0) { soundFileInfo.Artist = string.Join(";", tagFile.Tag.Performers).Trim(); // The AC/DC exception if (soundFileInfo.Artist.Contains("AC;DC")) { soundFileInfo.Artist = soundFileInfo.Artist.Replace("AC;DC", "AC/DC"); } } if (tagFile.Tag.FirstAlbumArtist != null) { soundFileInfo.AlbumArtist = tagFile.Tag.FirstAlbumArtist.Trim(); } if (tagFile.Tag.Album != null) { soundFileInfo.Album = tagFile.Tag.Album.Trim(); } if (tagFile.Tag.Title != null) { soundFileInfo.Title = tagFile.Tag.Title.Trim(); } if (tagFile.Tag.Comment != null) { soundFileInfo.Comment = tagFile.Tag.Comment.Trim(); } soundFileInfo.Year = (int)tagFile.Tag.Year; soundFileInfo.TrackNumber = (int)tagFile.Tag.Track; soundFileInfo.Genre = tagFile.Tag.FirstGenre; if (tagFile.Tag.FirstComposer != null) { soundFileInfo.Composer = tagFile.Tag.FirstComposer.Trim(); } // TODO!!! //soundFileInfo.Language = tagFile.Tag.Language.Trim(); /*if (id3Info.ID3v2Info.PlayCounter != null) * { * soundFileInfo.PlayCount = (int)id3Info.ID3v2Info.PlayCounter.Counter; * }*/ if (tagFile.Tag.Lyrics != null) { soundFileInfo.Lyrics = tagFile.Tag.Lyrics.Trim(); } // Rating ist eine Liste von Einträgen. Wir suchen hier nach dem Eintrag "*****@*****.**". TagLib.Id3v2.Tag id3v2Tag = tagFile.GetTag(TagLib.TagTypes.Id3v2) as TagLib.Id3v2.Tag; if (id3v2Tag != null) { TagLib.Id3v2.PopularimeterFrame popFrame = TagLib.Id3v2.PopularimeterFrame.Get(id3v2Tag, "*****@*****.**", false); if (popFrame != null) { soundFileInfo.Rating = popFrame.Rating; soundFileInfo.PlayCount = (int)popFrame.PlayCount; } } soundFileInfo.BPM = (int)tagFile.Tag.BeatsPerMinute; soundFileInfo.Length = (int)tagFile.Properties.Duration.TotalMilliseconds; soundFileInfo.Images = new List <byte[]>(); if (tagFile.Tag.Pictures.Length > 0) { foreach (TagLib.IPicture picture in tagFile.Tag.Pictures) { soundFileInfo.Images.Add(picture.Data.ToArray()); } } soundFileInfo.ID3Version = 2; if (soundFileInfo.Length == 0) { // Wenn in den ID3-Tags nichts drin stand, dann ermitteln wir die Länge über diesen Weg. soundFileInfo.Length = SoundEngine.GetLengthOfSoundfile(filename); } } } catch { // Zuerst mal hier alle Fehler ignorieren. } }
public async Task UpdateRating(int songId, int rating) { string path = DatabaseManager.GetFileInfo(songId).FilePath; try { StorageFile file = await StorageFile.GetFileFromPathAsync(path); using (Stream fileReadStream = await file.OpenStreamForReadAsync()) { using (Stream fileWriteStream = await file.OpenStreamForWriteAsync()) { using (File tagFile = TagLib.File.Create(new OwnFileAbstraction(file.Name, fileReadStream, fileWriteStream))) { if (tagFile.TagTypes.ToString().Contains(TagTypes.Id3v2.ToString())) { Tag tags = tagFile.GetTag(TagTypes.Id3v2); TagLib.Id3v2.PopularimeterFrame pop = TagLib.Id3v2.PopularimeterFrame.Get((TagLib.Id3v2.Tag)tags, "Windows Media Player 9 Series", true); if (pop != null) { if (rating == 5) { pop.Rating = 255; } else if (rating == 4) { pop.Rating = 196; } else if (rating == 3) { pop.Rating = 128; } else if (rating == 2) { pop.Rating = 64; } else if (rating == 1) { pop.Rating = 1; } else if (rating == 0) { pop.Rating = 0; } TagLib.Id3v2.Tag.DefaultVersion = 3; TagLib.Id3v2.Tag.ForceDefaultVersion = true; tagFile.Save(); } } } } } } catch (Exception ex) { Logger.Save("UpdateRating() " + Environment.NewLine + path + Environment.NewLine + ex.Message); Logger.SaveToFile(); } }
private async static Task <SongData> CreateSongFromFile(StorageFile file) { SongData song = new SongData(); song.DateAdded = DateTime.Now; song.Filename = file.Name; song.Path = file.Path; song.PlayCount = 0; song.LastPlayed = DateTime.MinValue; song.IsAvailable = 1; song.Tag.Rating = 0; song.FileSize = 0; try { using (Stream fileStream = await file.OpenStreamForReadAsync()) { try { var tagFile = TagLib.File.Create(new StreamFileAbstraction(file.Name, fileStream, fileStream)); try { song.Bitrate = (uint)tagFile.Properties.AudioBitrate; song.Duration = TimeSpan.FromSeconds(Convert.ToInt32(tagFile.Properties.Duration.TotalSeconds)); } catch (Exception ex) { song.Duration = TimeSpan.Zero; song.Bitrate = 0; } try { //TagLib.Id3v2.Tag.DefaultVersion = 3; //TagLib.Id3v2.Tag.ForceDefaultVersion = true; Tag tags; if (tagFile.TagTypes.ToString().Contains(TagTypes.Id3v2.ToString())) { tags = tagFile.GetTag(TagTypes.Id3v2); TagLib.Id3v2.PopularimeterFrame pop = TagLib.Id3v2.PopularimeterFrame.Get((TagLib.Id3v2.Tag)tags, "Windows Media Player 9 Series", false); if (pop != null) { if (224 <= pop.Rating && pop.Rating <= 255) { song.Tag.Rating = 5; } else if (160 <= pop.Rating && pop.Rating <= 223) { song.Tag.Rating = 4; } else if (96 <= pop.Rating && pop.Rating <= 159) { song.Tag.Rating = 3; } else if (32 <= pop.Rating && pop.Rating <= 95) { song.Tag.Rating = 2; } else if (1 <= pop.Rating && pop.Rating <= 31) { song.Tag.Rating = 1; } } } else if (tagFile.TagTypes.ToString().Contains(TagTypes.Id3v1.ToString())) { tags = tagFile.GetTag(TagTypes.Id3v1); } else if (tagFile.TagTypes.ToString().Contains(TagTypes.Apple.ToString())) { tags = tagFile.GetTag(TagTypes.Apple); } else { tags = tagFile.GetTag(tagFile.TagTypes); } song.Tag.Album = tags.Album ?? ""; song.Tag.AlbumArtist = tags.FirstAlbumArtist ?? ""; song.Tag.Artists = tags.JoinedPerformers ?? ""; song.Tag.Comment = tags.Comment ?? ""; song.Tag.Composers = tags.JoinedComposers ?? ""; song.Tag.Conductor = tags.Conductor ?? ""; song.Tag.Disc = (int)tags.Disc; song.Tag.DiscCount = (int)tags.DiscCount; song.Tag.FirstArtist = tags.FirstPerformer ?? ""; song.Tag.FirstComposer = tags.FirstComposer ?? ""; song.Tag.Genre = tags.FirstGenre ?? ""; song.Tag.Lyrics = tags.Lyrics ?? ""; song.Tag.Title = tags.Title ?? file.DisplayName; song.Tag.Track = (int)tags.Track; song.Tag.TrackCount = (int)tags.TrackCount; song.Tag.Year = (int)tags.Year; } catch (CorruptFileException e) { song.Tag.Album = ""; song.Tag.AlbumArtist = ""; song.Tag.Artists = ""; song.Tag.Comment = ""; song.Tag.Composers = ""; song.Tag.Conductor = ""; song.Tag.Disc = 0; song.Tag.DiscCount = 0; song.Tag.FirstArtist = ""; song.Tag.FirstComposer = ""; song.Tag.Genre = ""; song.Tag.Lyrics = ""; song.Tag.Title = file.DisplayName; song.Tag.Track = 0; song.Tag.TrackCount = 0; song.Tag.Year = 0; } } catch (Exception ex) { song.Tag.Album = ""; song.Tag.AlbumArtist = ""; song.Tag.Artists = ""; song.Tag.Comment = ""; song.Tag.Composers = ""; song.Tag.Conductor = ""; song.Tag.Disc = 0; song.Tag.DiscCount = 0; song.Tag.FirstArtist = ""; song.Tag.FirstComposer = ""; song.Tag.Genre = ""; song.Tag.Lyrics = ""; song.Tag.Title = file.DisplayName; song.Tag.Track = 0; song.Tag.TrackCount = 0; song.Tag.Year = 0; } } } catch (FileNotFoundException ex) { Logger.Save("CreateSongFromFile FileNotFound" + Environment.NewLine + ex.Message); Logger.SaveToFile(); song.FileSize = 0; song.IsAvailable = 0; song.Duration = TimeSpan.Zero; song.Bitrate = 0; song.Tag.Album = ""; song.Tag.AlbumArtist = ""; song.Tag.Artists = ""; song.Tag.Comment = ""; song.Tag.Composers = ""; song.Tag.Conductor = ""; song.Tag.Disc = 0; song.Tag.DiscCount = 0; song.Tag.FirstArtist = ""; song.Tag.FirstComposer = ""; song.Tag.Genre = ""; song.Tag.Lyrics = ""; song.Tag.Title = file.DisplayName; song.Tag.Track = 0; song.Tag.TrackCount = 0; song.Tag.Year = 0; return(song); } catch (Exception ex) { Logger.Save("CreateSongFromFile" + Environment.NewLine + ex.Message); Logger.SaveToFile(); song.FileSize = 0; } return(song); }
/// <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); } }
/// <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); } }