public ZuneMP3TagContainer(File file) : base(file) { //if we can't find the id3v2 tag we will create it, this will handle cases //where we load a tag with id3v1 only _tag = (Tag) file.GetTag(TagTypes.Id3v2, true); }
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); }
private TagLib.Tag ReadTag(ref long start) { long end = start; TagTypes type = ReadTagInfo(ref end); TagLib.Tag tag = null; switch (type) { case TagTypes.Ape: tag = new TagLib.Ape.Tag(file, start); break; case TagTypes.Id3v2: tag = new TagLib.Id3v2.Tag(file, start); break; } start = end; return(tag); }
// 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); } }
private static void SaveIsCompilation(TagLib.File file, bool is_compilation) { try { TagLib.Id3v2.Tag id3v2_tag = file.GetTag(TagLib.TagTypes.Id3v2, true) as TagLib.Id3v2.Tag; if (id3v2_tag != null) { id3v2_tag.IsCompilation = is_compilation; return; } } catch {} try { TagLib.Mpeg4.AppleTag apple_tag = file.GetTag(TagLib.TagTypes.Apple, true) as TagLib.Mpeg4.AppleTag; if (apple_tag != null) { apple_tag.IsCompilation = is_compilation; return; } } catch {} }
/// <summary> /// merge like values, hide unlike values /// </summary> public override void Coalesce() { FileInfo fi = (FileInfo)lv.SelectedItems[0].Tag; TagLib.File first_tag_file = TagLib.File.Create(fi.FullName); TagLib.Id3v2.Tag first_tag = tag_file.GetTag(TagLib.TagTypes.Id3v2) as TagLib.Id3v2.Tag; TagV2Ext first_tag_ext = new TagV2Ext(first_tag); foreach (ListViewItem item in lv.SelectedItems) { fi = (FileInfo)item.Tag; first_tag_file = TagLib.File.Create(fi.FullName); TagLib.Tag tag = tag_file.GetTag(TagLib.TagTypes.Id3v1); TagV2Ext tag_ext = new TagV2Ext(first_tag); if (tag != null) { } } v2 = first_tag; }
private void GetTags() { using (TagLib.File file = TagLib.File.Create(MediaFile.FullName)) { DateTime id3v1Start = DateTime.Now; try { TagLib.Id3v1.Tag v1Tag = (TagLib.Id3v1.Tag)file.GetTag(TagLib.TagTypes.Id3v1); ID3V1Tag = new TagLib.Id3v1.Tag(); v1Tag.CopyTo(ID3V1Tag, true); } catch { ID3V1Tag = null; } DateTime id3v1End = DateTime.Now; if (Globals.VerboseLogging) { Logger.Info($"'{MediaFile.FullName}' ID3V1 tag loaded in {(id3v1End - id3v1Start).TotalMilliseconds} milliseconds."); } DateTime id3v2Start = DateTime.Now; TagLib.Id3v2.Tag v2Tag = (TagLib.Id3v2.Tag)file.GetTag(TagLib.TagTypes.Id3v2); ID3V2Tag = new TagLib.Id3v2.Tag(); v2Tag.CopyTo(ID3V2Tag, true); DateTime id3v2End = DateTime.Now; if (Globals.VerboseLogging) { Logger.Info($"'{MediaFile.FullName}' ID3V2 tag loaded in {(id3v2End - id3v2Start).TotalMilliseconds} milliseconds."); } } ExecuteTagEdits(); }
public TagLib.Tag AddTag(TagTypes type, TagLib.Tag copy) { TagLib.Tag tag = null; if (type == TagTypes.Id3v2) { tag = new TagLib.Id3v2.Tag(); } else if (type == TagTypes.Ape) { tag = new TagLib.Ape.Tag(); (tag as Ape.Tag).HeaderPresent = true; } if (tag != null) { if (copy != null) { copy.CopyTo(tag, true); } AddTag(tag); } return(tag); }
/// <summary> /// Gets the tag information from an audio file. /// </summary> /// <param name="fullPath"></param> /// <returns></returns> public Tag OpenTag(string fullPath) { Tag tag = null; try { TagLib.File file = TagLib.File.Create(fullPath); mCurrentTagIsCompilation = false; if ((file.TagTypes & TagTypes.Id3v2) > 0) { TagLib.Id3v2.Tag iTag = (TagLib.Id3v2.Tag)file.GetTag(TagTypes.Id3v2); if (iTag.IsCompilation) { mCurrentTagIsCompilation = true; } return(iTag); } if ((file.TagTypes & TagTypes.Apple) > 0) { TagLib.Mpeg4.AppleTag iTag = (TagLib.Mpeg4.AppleTag)file.GetTag(TagTypes.Apple); if (iTag.IsCompilation) { mCurrentTagIsCompilation = true; } return(iTag); } // If not any of above tags, then try the default create. tag = file.Tag; } catch { return(null); } mCurrentTagIsCompilation = false; return(tag); }
public void LoadTagData(TagLib.Id3v2.Tag id3V2Tag, TagLib.Id3v1.Tag id3V1Tag, bool forceIDV2Tag = false) { ValidV1Tag = id3V1Tag != null; ValidV2Tag = id3V2Tag != null; if ((forceIDV2Tag && id3V2Tag == null) || (id3V1Tag == null && id3V2Tag == null)) { TagDataLoaded = false; return; } if (id3V2Tag != null) { LoadV2Tag(id3V2Tag); } else if (id3V1Tag != null) { LoadV1Tag(id3V1Tag); } TagDataLoaded = true; }
private static bool IsCompilation(TagLib.File file) { try { var xiph_tag = file.GetTag(TagLib.TagTypes.Xiph, true) as TagLib.Ogg.XiphComment; if (xiph_tag != null && xiph_tag.IsCompilation) { return(true); } } catch {} try { TagLib.Id3v2.Tag id3v2_tag = file.GetTag(TagLib.TagTypes.Id3v2, true) as TagLib.Id3v2.Tag; if (id3v2_tag != null && id3v2_tag.IsCompilation) { return(true); } } catch {} try { TagLib.Mpeg4.AppleTag apple_tag = file.GetTag(TagLib.TagTypes.Apple, true) as TagLib.Mpeg4.AppleTag; if (apple_tag != null && apple_tag.IsCompilation) { return(true); } } catch {} // FIXME the FirstAlbumArtist != FirstPerformer check might return true for half the // tracks on a compilation album, but false for some // TODO checked for 'Soundtrack' (and translated) in the title? if (file.Tag.Performers.Length > 0 && file.Tag.AlbumArtists.Length > 0 && (file.Tag.Performers.Length != file.Tag.AlbumArtists.Length || file.Tag.FirstAlbumArtist != file.Tag.FirstPerformer)) { return(true); } return(false); }
public virtual bool TryExtractMetadata(IResourceAccessor mediaItemAccessor, IDictionary <Guid, IList <MediaItemAspect> > extractedAspectData, bool importOnly, bool forceQuickMode) { IFileSystemResourceAccessor fsra = mediaItemAccessor as IFileSystemResourceAccessor; if (fsra == null) { return(false); } if (!fsra.IsFile) { return(false); } string fileName = fsra.ResourceName; if (!HasAudioExtension(fileName)) { return(false); } bool refresh = false; if (extractedAspectData.ContainsKey(AudioAspect.ASPECT_ID)) { refresh = true; } try { TrackInfo trackInfo = new TrackInfo(); if (refresh) { trackInfo.FromMetadata(extractedAspectData); } if (!trackInfo.IsBaseInfoPresent) { File tag = null; try { ByteVector.UseBrokenLatin1Behavior = true; // Otherwise we have problems retrieving non-latin1 chars tag = File.Create(new ResourceProviderFileAbstraction(fsra)); } catch (CorruptFileException) { // Only log at the info level here - And simply return false. This makes the importer know that we // couldn't perform our task here. ServiceRegistration.Get <ILogger>().Info("AudioMetadataExtractor: Audio file '{0}' seems to be broken", fsra.CanonicalLocalResourcePath); return(false); } using (tag) { // Some file extensions like .mp4 can contain audio and video. Do not handle files with video content here. if (tag.Properties.VideoHeight > 0 && tag.Properties.VideoWidth > 0) { return(false); } fileName = ProviderPathHelper.GetFileNameWithoutExtension(fileName) ?? string.Empty; string title; string sortTitle; string artist; uint? trackNo; GuessMetadataFromFileName(fileName, out title, out artist, out trackNo); if (!string.IsNullOrEmpty(title)) { title = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(title.ToLowerInvariant()); } if (!string.IsNullOrEmpty(artist)) { artist = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(artist.ToLowerInvariant()); } if (!string.IsNullOrEmpty(tag.Tag.Title)) { title = tag.Tag.Title.Trim(); } sortTitle = BaseInfo.GetSortTitle(title); if (!string.IsNullOrEmpty(tag.Tag.TitleSort)) { sortTitle = tag.Tag.TitleSort.Trim(); } IEnumerable <string> artists; if (tag.Tag.Performers.Length > 0) { artists = tag.Tag.Performers; if ((tag.TagTypes & TagTypes.Id3v2) != 0) { artists = PatchID3v23Enumeration(artists); } } else { artists = artist == null ? null : new string[] { artist.Trim() } }; if (tag.Tag.Track != 0) { trackNo = tag.Tag.Track; } if (importOnly) { MultipleMediaItemAspect providerResourceAspect = MediaItemAspect.CreateAspect(extractedAspectData, ProviderResourceAspect.Metadata); providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_RESOURCE_INDEX, 0); providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_PRIMARY, true); providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_SIZE, fsra.Size); providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH, fsra.CanonicalLocalResourcePath.Serialize()); // FIXME Albert: tag.MimeType returns taglib/mp3 for an MP3 file. This is not what we want and collides with the // mimetype handling in the BASS player, which expects audio/xxx. if (!string.IsNullOrWhiteSpace(tag.MimeType)) { providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_MIME_TYPE, tag.MimeType.Replace("taglib/", "audio/")); } MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_TITLE, title); MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_SORT_TITLE, sortTitle); MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_ISVIRTUAL, false); MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_COMMENT, StringUtils.TrimToNull(tag.Tag.Comment)); MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_RECORDINGTIME, fsra.LastChanged); } trackInfo.TrackName = title; trackInfo.TrackNameSort = sortTitle; if (tag.Properties.Codecs.Count() > 0) { trackInfo.Encoding = tag.Properties.Codecs.First().Description; } if (tag.Properties.Duration.TotalSeconds != 0) { trackInfo.Duration = (long)tag.Properties.Duration.TotalSeconds; } if (tag.Properties.AudioBitrate != 0) { trackInfo.BitRate = (int)tag.Properties.AudioBitrate; } if (tag.Properties.AudioChannels != 0) { trackInfo.Channels = (int)tag.Properties.AudioChannels; } if (tag.Properties.AudioSampleRate != 0) { trackInfo.SampleRate = (int)tag.Properties.AudioSampleRate; } TagLib.Id3v2.Tag id3Tag = (TagLib.Id3v2.Tag)tag.GetTag(TagTypes.Id3v2, false); if (id3Tag != null && !id3Tag.IsEmpty) { trackInfo.Compilation = id3Tag.IsCompilation; } trackInfo.Album = !string.IsNullOrEmpty(tag.Tag.Album) ? tag.Tag.Album.Trim() : null; if (!string.IsNullOrEmpty(tag.Tag.AlbumSort)) { IAudioRelationshipExtractor.StoreAlbum(extractedAspectData, tag.Tag.Album, tag.Tag.AlbumSort.Trim()); } if (trackNo.HasValue) { trackInfo.TrackNum = (int)trackNo.Value; } if (tag.Tag.TrackCount != 0) { trackInfo.TotalTracks = (int)tag.Tag.TrackCount; } if (tag.Tag.Disc != 0) { trackInfo.DiscNum = (int)tag.Tag.Disc; } if (tag.Tag.DiscCount != 0) { trackInfo.TotalDiscs = (int)tag.Tag.DiscCount; } if (!string.IsNullOrEmpty(tag.Tag.Lyrics)) { trackInfo.TrackLyrics = tag.Tag.Lyrics; } if (tag.Tag.TrackCount != 0) { trackInfo.TotalTracks = (int)tag.Tag.TrackCount; } if (!string.IsNullOrEmpty(tag.Tag.MusicBrainzTrackId)) { trackInfo.MusicBrainzId = tag.Tag.MusicBrainzTrackId; } if (!string.IsNullOrEmpty(tag.Tag.MusicBrainzReleaseId)) { trackInfo.AlbumMusicBrainzId = tag.Tag.MusicBrainzReleaseId; } if (!string.IsNullOrEmpty(tag.Tag.MusicBrainzDiscId)) { trackInfo.AlbumMusicBrainzDiscId = tag.Tag.MusicBrainzDiscId; } if (!string.IsNullOrEmpty(tag.Tag.AmazonId)) { trackInfo.AlbumAmazonId = tag.Tag.AmazonId; } if (!string.IsNullOrEmpty(tag.Tag.MusicIpId)) { trackInfo.MusicIpId = tag.Tag.MusicIpId; } trackInfo.Artists = new List <PersonInfo>(); if (artists != null) { foreach (string artistName in ApplyAdditionalSeparator(artists)) { trackInfo.Artists.Add(new PersonInfo() { Name = artistName.Trim(), Occupation = PersonAspect.OCCUPATION_ARTIST, ParentMediaName = trackInfo.Album, MediaName = trackInfo.TrackName }); } } //Save id if possible if (trackInfo.Artists.Count == 1 && !string.IsNullOrEmpty(tag.Tag.MusicBrainzArtistId)) { trackInfo.Artists[0].MusicBrainzId = tag.Tag.MusicBrainzArtistId; } IEnumerable <string> albumArtists = tag.Tag.AlbumArtists; if ((tag.TagTypes & TagTypes.Id3v2) != 0) { albumArtists = PatchID3v23Enumeration(albumArtists); } trackInfo.AlbumArtists = new List <PersonInfo>(); if (albumArtists != null) { foreach (string artistName in ApplyAdditionalSeparator(albumArtists)) { trackInfo.AlbumArtists.Add(new PersonInfo() { Name = artistName.Trim(), Occupation = PersonAspect.OCCUPATION_ARTIST, ParentMediaName = trackInfo.Album, MediaName = trackInfo.TrackName }); } } //Save id if possible if (trackInfo.AlbumArtists.Count == 1 && !string.IsNullOrEmpty(tag.Tag.MusicBrainzReleaseArtistId)) { trackInfo.AlbumArtists[0].MusicBrainzId = tag.Tag.MusicBrainzReleaseArtistId; } IEnumerable <string> composers = tag.Tag.Composers; if ((tag.TagTypes & TagTypes.Id3v2) != 0) { composers = PatchID3v23Enumeration(composers); } trackInfo.Composers = new List <PersonInfo>(); if (composers != null) { foreach (string composerName in ApplyAdditionalSeparator(composers)) { trackInfo.Composers.Add(new PersonInfo() { Name = composerName.Trim(), Occupation = PersonAspect.OCCUPATION_COMPOSER, ParentMediaName = trackInfo.Album, MediaName = trackInfo.TrackName }); } } if (tag.Tag.Genres.Length > 0) { IEnumerable <string> genres = tag.Tag.Genres; if ((tag.TagTypes & TagTypes.Id3v2) != 0) { genres = PatchID3v23Enumeration(genres); } trackInfo.Genres = ApplyAdditionalSeparator(genres).Select(s => new GenreInfo { Name = s.Trim() }).ToList(); OnlineMatcherService.Instance.AssignMissingMusicGenreIds(trackInfo.Genres); } int year = (int)tag.Tag.Year; if (year >= 30 && year <= 99) { year += 1900; } if (year >= 1930 && year <= 2030) { trackInfo.ReleaseDate = new DateTime(year, 1, 1); } if (!trackInfo.HasThumbnail) { // The following code gets cover art images from file (embedded) or from windows explorer cache (supports folder.jpg). IPicture[] pics = tag.Tag.Pictures; if (pics.Length > 0) { try { using (MemoryStream stream = new MemoryStream(pics[0].Data.Data)) { trackInfo.Thumbnail = stream.ToArray(); trackInfo.HasChanged = true; } } // Decoding of invalid image data can fail, but main MediaItem is correct. catch { } } else { // In quick mode only allow thumbs taken from cache. bool cachedOnly = importOnly || forceQuickMode; // Thumbnail extraction fileName = mediaItemAccessor.ResourcePathName; IThumbnailGenerator generator = ServiceRegistration.Get <IThumbnailGenerator>(); byte[] thumbData; ImageType imageType; if (generator.GetThumbnail(fileName, cachedOnly, out thumbData, out imageType)) { trackInfo.Thumbnail = thumbData; trackInfo.HasChanged = true; } } } } if (string.IsNullOrEmpty(trackInfo.Album) || trackInfo.Artists.Count == 0) { MusicNameMatcher.MatchTrack(fileName, trackInfo); } } //Determine compilation if (importOnly && !trackInfo.Compilation) { if (trackInfo.AlbumArtists.Count > 0 && (trackInfo.AlbumArtists[0].Name.IndexOf("Various", StringComparison.InvariantCultureIgnoreCase) >= 0 || trackInfo.AlbumArtists[0].Name.Equals("VA", StringComparison.InvariantCultureIgnoreCase))) { trackInfo.Compilation = true; } else { //Look for itunes compilation folder var mediaItemPath = mediaItemAccessor.CanonicalLocalResourcePath; var albumMediaItemDirectoryPath = ResourcePathHelper.Combine(mediaItemPath, "../"); var artistMediaItemDirectoryPath = ResourcePathHelper.Combine(mediaItemPath, "../../"); if (IsDiscFolder(trackInfo.Album, albumMediaItemDirectoryPath.FileName)) { //Probably a CD folder so try next parent artistMediaItemDirectoryPath = ResourcePathHelper.Combine(mediaItemPath, "../../../"); } if (artistMediaItemDirectoryPath.FileName.IndexOf("Compilation", StringComparison.InvariantCultureIgnoreCase) >= 0) { trackInfo.Compilation = true; } } } if (!refresh) { //Check artists trackInfo.Artists = GetCorrectedArtistsList(trackInfo, trackInfo.Artists); trackInfo.AlbumArtists = GetCorrectedArtistsList(trackInfo, trackInfo.AlbumArtists); } trackInfo.AssignNameId(); if (!forceQuickMode) { AudioCDMatcher.GetDiscMatchAndUpdate(mediaItemAccessor.ResourcePathName, trackInfo); if (SkipOnlineSearches && !SkipFanArtDownload) { TrackInfo tempInfo = trackInfo.Clone(); OnlineMatcherService.Instance.FindAndUpdateTrack(tempInfo, importOnly); trackInfo.CopyIdsFrom(tempInfo); trackInfo.HasChanged = tempInfo.HasChanged; } else if (!SkipOnlineSearches) { OnlineMatcherService.Instance.FindAndUpdateTrack(trackInfo, importOnly); } } if (refresh) { if ((IncludeArtistDetails && !BaseInfo.HasRelationship(extractedAspectData, PersonAspect.ROLE_ARTIST) && trackInfo.Artists.Count > 0) || (IncludeArtistDetails && !BaseInfo.HasRelationship(extractedAspectData, PersonAspect.ROLE_ALBUMARTIST) && trackInfo.AlbumArtists.Count > 0) || (IncludeComposerDetails && !BaseInfo.HasRelationship(extractedAspectData, PersonAspect.ROLE_COMPOSER) && trackInfo.Composers.Count > 0)) { trackInfo.HasChanged = true; } } if (!trackInfo.HasChanged && !importOnly) { return(false); } trackInfo.SetMetadata(extractedAspectData); if (importOnly) { //Store metadata for the Relationship Extractors if (IncludeArtistDetails) { IAudioRelationshipExtractor.StorePersons(extractedAspectData, trackInfo.Artists, false); IAudioRelationshipExtractor.StorePersons(extractedAspectData, trackInfo.AlbumArtists, true); } if (IncludeComposerDetails) { IAudioRelationshipExtractor.StorePersons(extractedAspectData, trackInfo.Composers, false); } } return(trackInfo.IsBaseInfoPresent); } catch (UnsupportedFormatException) { ServiceRegistration.Get <ILogger>().Info("AudioMetadataExtractor: Unsupported audio file '{0}'", fsra.CanonicalLocalResourcePath); return(false); } catch (Exception e) { // Only log at the info level here - And simply return false. This makes the importer know that we // couldn't perform our task here ServiceRegistration.Get <ILogger>().Info("AudioMetadataExtractor: Exception reading resource '{0}' (Text: '{1}')", fsra.CanonicalLocalResourcePath, e.Message); } return(false); }
private async void Button_Convert_Click(object sender, RoutedEventArgs e) { ((Button)e.Source).IsEnabled = false; Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); var temp = FileList.Where(x => x.IsChecked).ToList(); string ErrorMessage = null; foreach (var _temp in temp) { Mouse.OverrideCursor = Cursors.Wait; stopwatch.Start(); try { var tfile = TagLib.File.Create(Path.Combine(_temp.Path, _temp.Name)); tfile.RemoveTags((Enable_ID3v1 ? TagLib.TagTypes.None : TagLib.TagTypes.Id3v1) | (Enable_ID3v2 ? TagLib.TagTypes.None : TagLib.TagTypes.Id3v2)); TagLib.Id3v1.Tag t = (TagLib.Id3v1.Tag)tfile.GetTag(TagLib.TagTypes.Id3v1, Enable_ID3v1 ? true : false); TagLib.Id3v2.Tag t2 = (TagLib.Id3v2.Tag)tfile.GetTag(TagLib.TagTypes.Id3v2, Enable_ID3v2 ? true : false); SetID3v2Encoding(Encoding_Output_ID3v2); if (t != null) { var TagList = GetAllStringProperties(t); var Dic = TagList.ToDictionary(x => x.TagName, x => StringToUnicode.TryToConvertLatin1ToUnicode(x.Value, encoding[0])); var resoult = ConvertEncoding ? await ConvertHelper.ConvertDictionary(Dic, encoding, ToChinese1) : await ConvertHelper.ConvertDictionary(Dic, ToChinese1); resoult.ToList().ForEach(x => t.SetPropertiesValue(x.Key, Encoding.GetEncoding("ISO-8859-1").GetString(encoding[1].GetBytes(x.Value)))); } if (t2 != null) { var TagList = GetAllStringProperties(t2); var Dic = TagList.ToDictionary(x => x.TagName, x => { if (tfile.TagTypesOnDisk.HasFlag(TagLib.TagTypes.Id3v2)) { return(StringToUnicode.TryToConvertLatin1ToUnicode(x.Value, encoding2[0])); } else { var _ = ID3v1_TagList.Where(y => y.TagName == x.TagName).FirstOrDefault(); return(_ != null ? _.Value_Preview : ""); } }); var resoult = await ConvertHelper.ConvertDictionary(Dic, ToChinese2); resoult.ToList().ForEach(x => t.SetPropertiesValue(x.Key, x.Value)); t2.Version = (Combobox_ID3v2_Version.Text == "2.3") ? (byte)3 : (byte)4; } tfile.Save(); } catch (TagLib.UnsupportedFormatException) { ErrorMessage = string.Format("轉換{0}時出現錯誤,該檔案並非音訊檔", _temp.Name); } catch (FanhuajiException val) { ErrorMessage = ((Exception)val).Message; break; } catch { ErrorMessage = string.Format("轉換{0}時出現未知錯誤", _temp.Name); } } Mouse.OverrideCursor = null; stopwatch.Stop(); if (!string.IsNullOrEmpty(ErrorMessage)) { Window_MessageBoxEx.ShowDialog(ErrorMessage, "轉換過程中出現錯誤", "我知道了"); } else if (App.Settings.Prompt) { new Toast(string.Format("轉換完成\r\n耗時:{0} ms", stopwatch.ElapsedMilliseconds)).Show(); } ((Button)e.Source).IsEnabled = true; Listview_SelectionChanged(null, null); }
public static TagLib.File ConvertMusicFileTagToTag(MusicFileTag musicTag) { TagLib.File tagInfo = TagLib.File.Create(musicTag.FilePath); // V1 if (!musicTag.EnabledV1) { tagInfo.RemoveTags(TagTypes.Id3v1); } else { tagInfo.GetTag(TagTypes.Id3v1).Performers = new string[] { musicTag.ArtistV1 ?? "" }; tagInfo.GetTag(TagTypes.Id3v1).Genres = new string[] { musicTag.GenreV1 ?? "" }; tagInfo.GetTag(TagTypes.Id3v1).Album = musicTag.AlbumV1 ?? ""; tagInfo.GetTag(TagTypes.Id3v1).Title = musicTag.TitleV1 ?? ""; tagInfo.GetTag(TagTypes.Id3v1).Comment = musicTag.CommentV1 ?? ""; int.TryParse(musicTag.YearV1, out int tmpYearV1); if (tmpYearV1 > 0) { tagInfo.GetTag(TagTypes.Id3v1).Year = (uint)tmpYearV1; } int.TryParse(musicTag.TrackV1, out int tmpTrackV1); if (tmpTrackV1 > 0) { tagInfo.GetTag(TagTypes.Id3v1).Track = (uint)tmpTrackV1; } } // V2 if (!musicTag.EnabledV2) { tagInfo.RemoveTags(TagTypes.Id3v2); } else { TagLib.Id3v2.Tag id3v2Tag = tagInfo.GetTag(TagTypes.Id3v2) as TagLib.Id3v2.Tag; id3v2Tag.Version = Convert.ToByte(musicTag.VersionV2); id3v2Tag.SetTextFrame("TDLY", musicTag.PlayListDelayV2); id3v2Tag.SetTextFrame("TRCK", musicTag.TrackNumberV2); id3v2Tag.SetTextFrame("TPOS", musicTag.PartOfSetV2); id3v2Tag.SetTextFrame("TBPM", musicTag.BPMV2); id3v2Tag.SetTextFrame("TPE1", musicTag.ArtistV2); id3v2Tag.SetTextFrame("TCON", musicTag.GenreV2); id3v2Tag.SetTextFrame("TLAN", musicTag.LanguageV2); id3v2Tag.SetTextFrame("TKEY", musicTag.KeyV2); id3v2Tag.SetTextFrame("TSST", musicTag.SetSubtitleV2); id3v2Tag.SetTextFrame("TIT1", musicTag.ContentDescriptionV2); id3v2Tag.SetTextFrame("TMOO", musicTag.MoodV2); id3v2Tag.SetTextFrame("TPE4", musicTag.InterpretedV2); id3v2Tag.SetTextFrame("TSOA", musicTag.AlbumSortV2); id3v2Tag.SetTextFrame("TALB", musicTag.AlbumV2); id3v2Tag.SetTextFrame("TIT3", musicTag.SubtitleV2); id3v2Tag.SetTextFrame("TSOT", musicTag.TitleSortV2); id3v2Tag.SetTextFrame("TIT2", musicTag.TitleV2); /// Frames from /// http://id3.org/id3v2.3.0#Declared_ID3v2_frames } return(tagInfo); }
private void Button_Convert_Click(object sender, RoutedEventArgs e) { ((Button)e.Source).IsEnabled = false; Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); var temp = FileList.Where(x => x.IsChecked).ToList(); foreach (var _temp in temp) { Mouse.OverrideCursor = Cursors.Wait; stopwatch.Start(); switch (Encoding_Output_ID3v2) { case "UTF-8": TagLib.Id3v2.Tag.DefaultEncoding = TagLib.StringType.UTF8; break; case "UTF-16": TagLib.Id3v2.Tag.DefaultEncoding = TagLib.StringType.UTF16; break; case "UTF-16BE": TagLib.Id3v2.Tag.DefaultEncoding = TagLib.StringType.UTF16BE; break; case "UTF-16LE": TagLib.Id3v2.Tag.DefaultEncoding = TagLib.StringType.UTF16LE; break; } try { var tfile = TagLib.File.Create(Path.Combine(_temp.Path, _temp.Name)); tfile.RemoveTags((Enable_ID3v1 ? TagLib.TagTypes.None : TagLib.TagTypes.Id3v1) | (Enable_ID3v2 ? TagLib.TagTypes.None : TagLib.TagTypes.Id3v2)); TagLib.Id3v1.Tag t = (TagLib.Id3v1.Tag)tfile.GetTag(TagLib.TagTypes.Id3v1); TagLib.Id3v2.Tag t2 = (TagLib.Id3v2.Tag)tfile.GetTag(TagLib.TagTypes.Id3v2, Enable_ID3v1 ? true : false); GetAllStringProperties(t).ForEach(x => { x.Value = encoding[1].GetString(Encoding.GetEncoding("ISO-8859-1").GetBytes(x.Value)); x.Value_Preview = ConvertHelper.Convert(x.Value, encoding, ToChinese1); SetPropertiesValue(t, x.TagName, Encoding.GetEncoding("ISO-8859-1").GetString(encoding[1].GetBytes(x.Value_Preview))); }); GetAllStringProperties(t2).ForEach(x => { x.Value_Preview = ConvertHelper.Convert(x.Value, ToChinese2); SetPropertiesValue(t2, x.TagName, x.Value_Preview); }); t2.Version = (Combobox_ID3v2_Version.Text == "2.3") ? (byte)3 : (byte)4; tfile.Save(); } catch (TagLib.UnsupportedFormatException) { MessageBox.Show(string.Format("轉換{0}時出現錯誤,該檔案並非音訊檔", _temp.Name)); } catch { MessageBox.Show(string.Format("轉換{0}時出現未知錯誤", _temp.Name)); } Mouse.OverrideCursor = null; } stopwatch.Stop(); if (App.Settings.Prompt) { MessageBox.Show(string.Format("轉換完成\r\n耗時:{0} ms", stopwatch.ElapsedMilliseconds)); } ((Button)e.Source).IsEnabled = true; Listview_SelectionChanged(null, null); }
/// <summary> /// Reads a tag ending at a specified position and moves the /// cursor to its start position. /// </summary> /// <param name="end"> /// A <see cref="long" /> value reference specifying at what /// position the potential tag ends at. If a tag is found, /// this value will be updated to the position at which the /// found tag starts. /// </param> /// <returns> /// A <see cref="TagLib.Tag" /> object representing the tag /// found at the specified position, or <see langword="null" /// /> if no tag was found. /// </returns> private TagLib.Tag ReadTag(ref long end) { long start = end; TagTypes type = ReadTagInfo (ref start); TagLib.Tag tag = null; try { switch (type) { case TagTypes.Ape: tag = new TagLib.Ape.Tag (file, end - TagLib.Ape.Footer.Size); break; case TagTypes.Id3v2: tag = new TagLib.Id3v2.Tag (file, start); break; case TagTypes.Id3v1: tag = new TagLib.Id3v1.Tag (file, start); break; } end = start; } catch (CorruptFileException) { } return tag; }
/// <summary> /// 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> /// insert / update a song in database /// </summary> /// <param name="tag">id3 tag</param> /// <param name="tag_file">id3 tag file</param> /// <param name="art_id">sql art id</param> /// <param name="artist_id">sql artist id</param> /// <param name="album_id">sql album id</param> private object InsertSong( TagLib.Tag tag, TagLib.File tag_file, string art_id, object artist_id, object album_id) { // format the timespane (H:M:SS) TimeSpan ts = tag_file.Properties.Duration; string h = ts.Hours != 0 ? ts.Hours.ToString() + ":" : ""; string m = ts.Minutes != 0 ? ts.Minutes.ToString() : "0"; string s = ts.Seconds < 10 ? "0" + ts.Seconds.ToString() : ts.Seconds.ToString(); StringBuilder length = new StringBuilder(h + m + ":" + s); StringBuilder file = new StringBuilder(tag_file.Name); StringBuilder lyrics = ((tag.Lyrics != null) && (tag.Lyrics != string.Empty)) ? new StringBuilder(tag.Lyrics) : null; // change path to unix style file.Remove(0, 2); file.Replace('\\', '/'); object song_id = GetKey("song", "file", file.ToString()); MySqlCommand cmd = new MySqlCommand(); cmd.Parameters.AddWithValue("?artist_id", artist_id); cmd.Parameters.AddWithValue("?album_id", album_id); cmd.Parameters.AddWithValue("?track", tag.Track); cmd.Parameters.AddWithValue("?title", tag.Title); cmd.Parameters.AddWithValue("?file", file); cmd.Parameters.AddWithValue("?genre", tag.FirstGenre); cmd.Parameters.AddWithValue("?bitrate", tag_file.Properties.AudioBitrate.ToString()); cmd.Parameters.AddWithValue("?length", length); // (MySql Year) the allowable values are 1901 to 2155, and 0000 string year = (tag.Year == 0000 || (tag.Year > 1900 && tag.Year < 2155)) ? tag.Year.ToString() : "0000"; cmd.Parameters.AddWithValue("?year", year); cmd.Parameters.AddWithValue("?comments", tag.Comment); TagLib.Id3v2.Tag idv2 = null; try { idv2 = tag_file.GetTag(TagLib.TagTypes.Id3v2) as TagLib.Id3v2.Tag; } catch (Exception e) { // taglib throws an exception on some file types? OnError(e.Message); } string encoder = "NA"; if (idv2 != null) { TagLib.Id3v2.TextInformationFrame frame = TagLib.Id3v2.TextInformationFrame.Get((TagLib.Id3v2.Tag)idv2, "TSSE", false); encoder = frame != null && frame.Text.Length > 0 ? frame.Text[0] : "Unknown"; } cmd.Parameters.AddWithValue("?encoder", encoder); cmd.Parameters.AddWithValue("?file_size", tag_file.Length.ToString()); cmd.Parameters.AddWithValue("?file_type", tag_file.MimeType); cmd.Parameters.AddWithValue("?art_id", art_id); cmd.Parameters.AddWithValue("?lyrics", lyrics); cmd.Parameters.AddWithValue("?composer", tag.FirstComposer); cmd.Parameters.AddWithValue("?conductor", tag.Conductor); cmd.Parameters.AddWithValue("?copyright", tag.Copyright); cmd.Parameters.AddWithValue("?disc", tag.Disc); cmd.Parameters.AddWithValue("?disc_count", tag.DiscCount); cmd.Parameters.AddWithValue("?performer", tag.FirstPerformer); cmd.Parameters.AddWithValue("?tag_types", tag.TagTypes.ToString()); cmd.Parameters.AddWithValue("?track_count", tag.TrackCount); cmd.Parameters.AddWithValue("?beats_per_minute", tag.BeatsPerMinute); cmd.Parameters.AddWithValue("?song_id", song_id); byte[] sha1 = null; if (Settings.Default.compute_sha1) { sha1 = TagLibExt.MediaSHA1(tag_file); string hex = Utility.Functions.Bytes2HexString(sha1); Trace.WriteLine("SHA1 - " + hex, Logger.Level.Information.ToString()); } cmd.Parameters.AddWithValue("?sha1", sha1); string sql = string.Empty; if (song_id == null) { sql = "INSERT INTO song (artist_id, album_id, track, title, file, genre, bitrate, length, year, comments, " + "encoder, file_size, file_type, art_id, lyrics, composer, conductor, copyright, " + "disc, disc_count, performer, tag_types, track_count, beats_per_minute, sha1) VALUES(" + "?artist_id, ?album_id, ?track, ?title, ?file, ?genre, ?bitrate, ?length, ?year, ?comments, " + "?encoder, ?file_size, ?file_type, ?art_id, ?lyrics, ?composer, ?conductor, ?copyright, " + "?disc, ?disc_count, ?performer, ?tag_types, ?track_count, ?beats_per_minute, ?sha1)"; OnMessage("INSERTED SONG: " + Path.GetFileName(tag_file.Name)); cmd.CommandText = sql; mysql_connection.ExecuteNonQuery(cmd); song_id = mysql_connection.LastInsertID; reporter.InsertSongCount++; } else { sql = "UPDATE song SET artist_id=?artist_id, album_id=?album_id, track=?track, title=?title, file=?file, genre=?genre, " + "bitrate=?bitrate, length=?length, year=?year, comments=?comments, encoder=?encoder, file_size=?file_size, file_type=?file_type, " + "art_id=?art_id, lyrics=?lyrics, composer=?composer, conductor=?conductor, copyright=?copyright, disc=?disc, disc_count=?disc_count, " + "performer=?performer, tag_types=?tag_types, track_count=?track_count, beats_per_minute=?beats_per_minute, sha1=?sha1 " + "WHERE id = ?song_id"; OnMessage("UPDATED SONG: " + Path.GetFileName(tag_file.Name)); cmd.CommandText = sql; mysql_connection.ExecuteNonQuery(cmd); reporter.UpdateSongCount++; } return(song_id); }
/// <summary> /// Reads a tag starting at a specified position and moves the /// cursor to its start position. /// </summary> /// <param name="start"> /// A <see cref="long" /> value reference specifying at what /// position the potential tag starts. If a tag is found, /// this value will be updated to the position at which the /// found tag ends. /// </param> /// <returns> /// A <see cref="TagLib.Tag" /> object representing the tag /// found at the specified position, or <see langword="null" /// /> if no tag was found. /// </returns> private TagLib.Tag ReadTag(ref long start) { long end = start; TagTypes type = ReadTagInfo (ref end); TagLib.Tag tag = null; try { switch (type) { case TagTypes.Ape: tag = new TagLib.Ape.Tag (file, start); break; case TagTypes.Id3v2: tag = new TagLib.Id3v2.Tag (file, start); break; } } catch (CorruptFileException e) { Console.Error.WriteLine ("taglib-sharp caught exception creating tag: {0}", e); } start = end; return tag; }
/// <summary> /// 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); } }
/// <summary> /// Update tags for single song /// </summary> public static void UpdateSingleTag(Song song) { try { using (TagLib.File taglibFile = TagLib.File.Create(song.FileName)) { if (taglibFile.Tag != null) { if (!string.IsNullOrEmpty(taglibFile.Tag.Title)) { song.Name = taglibFile.Tag.Title.Trim(); } if (!string.IsNullOrEmpty(taglibFile.Tag.JoinedPerformers)) { song.Artist = taglibFile.Tag.JoinedPerformers.Trim(); } if (!string.IsNullOrEmpty(taglibFile.Tag.JoinedGenres)) { song.Genre = taglibFile.Tag.JoinedGenres.Trim(); } if (!string.IsNullOrEmpty(taglibFile.Tag.Album)) { song.Album = taglibFile.Tag.Album.Trim(); } int rating = int.MinValue; if (taglibFile.Tag.TagTypes.HasFlag(TagLib.TagTypes.Id3v2)) { TagLib.Id3v2.Tag id3v2Tag = (TagLib.Id3v2.Tag)taglibFile.GetTag(TagLib.TagTypes.Id3v2); List <TagLib.Id3v2.PopularimeterFrame> popularimeterFrames = id3v2Tag .Where(x => x is TagLib.Id3v2.PopularimeterFrame) .Cast <TagLib.Id3v2.PopularimeterFrame>() .OrderBy(y => y.User) .ToList(); if (popularimeterFrames != null && popularimeterFrames.Count > 0) { foreach (TagLib.Id3v2.PopularimeterFrame popularimeterFrame in popularimeterFrames) { if (popularimeterFrame.Rating > 0) { rating = popularimeterFrame.Rating; break; } } } } if (rating == 0) { song.Rating = 1; } else if (rating == 1) { song.Rating = 2; } else if (rating > 1 && rating < 64) { song.Rating = 3; } else if (rating == 64) { song.Rating = 4; } else if (rating > 64 && rating < 128) { song.Rating = 5; } else if (rating == 128) { song.Rating = 6; } else if (rating > 128 && rating < 196) { song.Rating = 7; } else if (rating == 196) { song.Rating = 8; } else if (rating > 196 && rating < 255) { song.Rating = 9; } else if (rating == 255) { song.Rating = 10; } else { song.Rating = -1; } song.Duration = (int)taglibFile.Properties.Duration.TotalSeconds; uint year = taglibFile.Tag.Year; song.Year = year > 0 ? year.ToString() : string.Empty; FileInfo fileInfo = new FileInfo(song.FileName); song.DateCreated = fileInfo.CreationTime.ToString("yyyy-MM-dd HH:mm"); song.GenerateSearchAndDoubleMetaphone(); } } song.TagRead = true; song.ErrorReadingTag = false; } catch (System.IO.IOException) { song.TagRead = false; song.ErrorReadingTag = true; } catch (Exception) { song.TagRead = true; } }
private void Button_Convert_Click(object sender, RoutedEventArgs e) { ((Button)e.Source).IsEnabled = false; Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); var temp = FileList.Where(x => x.IsChecked).ToList(); foreach (var _temp in temp) { Mouse.OverrideCursor = Cursors.Wait; stopwatch.Start(); try { var tfile = TagLib.File.Create(Path.Combine(_temp.Path, _temp.Name)); tfile.RemoveTags((Enable_ID3v1 ? TagLib.TagTypes.None : TagLib.TagTypes.Id3v1) | (Enable_ID3v2 ? TagLib.TagTypes.None : TagLib.TagTypes.Id3v2)); TagLib.Id3v1.Tag t = (TagLib.Id3v1.Tag)tfile.GetTag(TagLib.TagTypes.Id3v1, Enable_ID3v1 ? true : false); TagLib.Id3v2.Tag t2 = (TagLib.Id3v2.Tag)tfile.GetTag(TagLib.TagTypes.Id3v2, Enable_ID3v2 ? true : false); SetID3v2Encoding(Encoding_Output_ID3v2); if (t != null) { GetAllStringProperties(t).ForEach(x => { x.Value = StringToUnicode.TryToConvertLatin1ToUnicode(x.Value, encoding[0]); x.Value_Preview = ConvertEncoding ? ConvertHelper.Convert(x.Value, encoding, ToChinese1) : ConvertHelper.Convert(x.Value, ToChinese1); t.SetPropertiesValue(x.TagName, Encoding.GetEncoding("ISO-8859-1").GetString(encoding[1].GetBytes(x.Value_Preview))); }); } if (t2 != null) { GetAllStringProperties(t2).ForEach(x => { if (tfile.TagTypesOnDisk.HasFlag(TagLib.TagTypes.Id3v2)) { x.Value = StringToUnicode.TryToConvertLatin1ToUnicode(x.Value, encoding2[0]); } else { var _ = ID3v1_TagList.Where(y => y.TagName == x.TagName).FirstOrDefault(); x.Value = _ != null ? _.Value_Preview : ""; } x.Value_Preview = ConvertHelper.Convert(x.Value, ToChinese2); t2.SetPropertiesValue(x.TagName, x.Value_Preview); }); t2.Version = (Combobox_ID3v2_Version.Text == "2.3") ? (byte)3 : (byte)4; } tfile.Save(); } catch (TagLib.UnsupportedFormatException) { MessageBox.Show(string.Format("轉換{0}時出現錯誤,該檔案並非音訊檔", _temp.Name)); } catch { MessageBox.Show(string.Format("轉換{0}時出現未知錯誤", _temp.Name)); } } Mouse.OverrideCursor = null; stopwatch.Stop(); if (App.Settings.Prompt) { new Toast(string.Format("轉換完成\r\n耗時:{0} ms", stopwatch.ElapsedMilliseconds)).Show(); } ((Button)e.Source).IsEnabled = true; Listview_SelectionChanged(null, null); }
private void Preview(string path) { if (!File.Exists(path)) { return; } try { var tfile = TagLib.File.Create(path, TagLib.ReadStyle.None); TagLib.Id3v1.Tag t = (TagLib.Id3v1.Tag)tfile.GetTag(TagLib.TagTypes.Id3v1); TagLib.Id3v2.Tag t2 = (TagLib.Id3v2.Tag)tfile.GetTag(TagLib.TagTypes.Id3v2); ID3v1_TagList.Clear(); ID3v2_TagList.Clear(); GetAllStringProperties(t).ForEach(x => { x.Value = StringToUnicode.TryToConvertLatin1ToUnicode(x.Value, encoding[0]); x.Value_Preview = ConvertEncoding ? ConvertHelper.Convert(x.Value, encoding, ToChinese1) : ConvertHelper.Convert(x.Value, ToChinese1); ID3v1_TagList.Add(x); }); GetAllStringProperties(t2).ForEach(x => { if (tfile.TagTypesOnDisk.HasFlag(TagLib.TagTypes.Id3v2)) { x.Value = StringToUnicode.TryToConvertLatin1ToUnicode(x.Value, encoding2[0]); } else { var _ = ID3v1_TagList.Where(y => y.TagName == x.TagName).FirstOrDefault(); x.Value = _ != null ? _.Value_Preview : ""; } x.Value_Preview = ConvertHelper.Convert(x.Value, ToChinese2); ID3v2_TagList.Add(x); }); } catch (TagLib.UnsupportedFormatException) { ID3v1_TagList.Clear(); ID3v2_TagList.Clear(); ID3v1_TagList.Add(new TagList_Line() { TagName = "Error", Value = "非音訊檔" }); ID3v2_TagList.Add(new TagList_Line() { TagName = "Error", Value = "非音訊檔" }); } catch (System.Exception) { ID3v1_TagList.Clear(); ID3v2_TagList.Clear(); ID3v1_TagList.Add(new TagList_Line() { TagName = "Error", Value = "未知" }); ID3v2_TagList.Add(new TagList_Line() { TagName = "Error", Value = "未知" }); } }
private Tag GetId3Tag() { var uri = new Uri(String.Format("https://gdata.youtube.com/feeds/api/videos/{0}?v=2", _youtubeEntry.YoutubeUrl.Id)); var tag = new Tag { Title = _youtubeEntry.Title, Album = _youtubeEntry.ChannelName }; try { var xml = new XmlDocument(); var req = WebRequest.Create(uri); using (var resp = req.GetResponse()) { using (var stream = resp.GetResponseStream()) { if (stream != null) xml.Load(stream); } } if (xml.DocumentElement != null) { var manager = new XmlNamespaceManager(xml.NameTable); manager.AddNamespace("root", "http://www.w3.org/2005/Atom"); manager.AddNamespace("app", "http://www.w3.org/2007/app"); manager.AddNamespace("media", "http://search.yahoo.com/mrss/"); manager.AddNamespace("gd", "http://schemas.google.com/g/2005"); manager.AddNamespace("yt", "http://gdata.youtube.com/schemas/2007"); tag.Title = GetText(xml, "media:group/media:title", manager); tag.Lyrics = "MS.Video.Downloader\r\n" + GetText(xml, "media:group/media:description", manager); tag.Copyright = GetText(xml, "media:group/media:license", manager); tag.Album = _youtubeEntry.ChannelName; tag.Composers = new[] { "MS.Video.Downloader", "Youtube", GetText(xml, "root:link[@rel=\"alternate\"]/@href", manager), GetText(xml, "root:author/root:name", manager), GetText(xml, "root:author/root:uri", manager) }; var urlNodes = xml.DocumentElement.SelectNodes("media:group/media:thumbnail", manager); var webClient = new WebClient(); var pics = new List<IPicture>(); if (urlNodes != null && urlNodes.Count > 0) { foreach (XmlNode urlNode in urlNodes) { var attributes = urlNode.Attributes; if (attributes == null || attributes.Count <= 0) continue; var url = attributes["url"]; if (url == null || String.IsNullOrEmpty(url.Value)) continue; var data = webClient.DownloadData(url.Value); IPicture pic = new Picture(new ByteVector(data)); pics.Add(pic); } } tag.Pictures = pics.ToArray(); } } catch { } return tag; }
private void LoadV2Tag(TagLib.Id3v2.Tag id3Tag) { Album = id3Tag.Album; Artist = id3Tag.JoinedPerformers; AlbumArtist = id3Tag.JoinedAlbumArtists; DiscNumber = id3Tag.Disc != 0 ? id3Tag.Disc.ToString() : ""; DiscCount = id3Tag.DiscCount != 0 ? id3Tag.DiscCount.ToString() : ""; DiscNumberAndCount = id3Tag.Frames.Any(f => f.FrameId.ToString() == "TPOS") ? id3Tag.Frames.First(f => f.FrameId.ToString() == "TPOS").ToString() : ""; TrackNumber = id3Tag.Track.ToString(); Year = id3Tag.Year == 0 ? "0000" : id3Tag.Year.ToString(); Genre = id3Tag.JoinedGenres; Title = id3Tag.Title; ContainsOtherTags = id3Tag.Frames.Any(f => !ValidFrameNames.Contains(f.FrameId.ToString())); if (ContainsOtherTags) { List <string> invalidTagsDescriptions = new List <string>(); var invalidTagsFrameIDs = id3Tag.Frames.Where(f => !ValidFrameNames.Contains(f.FrameId.ToString())).ToList(); foreach (var frame in invalidTagsFrameIDs) { try { //The frame can be of multiple types, so let's try and get the description var frameProperties = frame.GetType().GetProperties(); var frameDescription = frameProperties.FirstOrDefault(p => p.Name == "Description"); var descriptionValue = (string)frameDescription.GetValue(frame, null); if (string.IsNullOrWhiteSpace(descriptionValue)) { if (Data.ID3V2Definitions.FrameDefintions.ContainsKey(frame.FrameId.ToString())) { descriptionValue = Data.ID3V2Definitions.FrameDefintions[frame.FrameId.ToString()]; } else { descriptionValue = frame.FrameId.ToString(); } } invalidTagsDescriptions.Add(descriptionValue); frameDescription = null; frameProperties = null; } catch { if (Data.ID3V2Definitions.FrameDefintions.ContainsKey(frame.FrameId.ToString())) { invalidTagsDescriptions.Add(Data.ID3V2Definitions.FrameDefintions[frame.FrameId.ToString()]); } else { invalidTagsDescriptions.Add(frame.FrameId.ToString()); } } } OtherTags = string.Join(",", invalidTagsDescriptions); if ((OtherTags.ToLower() == "totaldiscs,totaltracks" || OtherTags.ToLower() == "totaltracks,totaldiscs" || OtherTags.ToLower() == "totaldiscs" || OtherTags.ToLower() == "totaltracks") && IgnoreITunesTotalTags) { ContainsOtherTags = false; OtherTags = ""; } } else { OtherTags = ""; } }
/// <summary> /// init item /// </summary> public bool IntializeItem() { try { tag_file = TagLib.File.Create(fi.FullName); v1 = tag_file.GetTag(TagLib.TagTypes.Id3v1) as TagLib.Id3v1.Tag; v2 = tag_file.GetTag(TagLib.TagTypes.Id3v2) as TagLib.Id3v2.Tag; } catch (TagLib.CorruptFileException e) { // BKP todo // humm, what shall we do? log? System.Diagnostics.Trace.WriteLine(e.Message); return(false); } Win32.SHFILEINFO sInfo = new OS.Win32.Win32.SHFILEINFO(); // Use this to get the small Icon IntPtr handle = Win32.SHGetFileInfo(fi.FullName, 0, ref sInfo, (uint)Marshal.SizeOf(sInfo), Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON); if (lv.SmallImageList.Images.ContainsKey(sInfo.dwAttributes.ToString()) != true) { // The icon is returned in the hIcon member of the shinfo struct System.Drawing.Icon icon = System.Drawing.Icon.FromHandle(sInfo.hIcon); lv.SmallImageList.Images.Add(sInfo.dwAttributes.ToString(), icon); } this.ImageIndex = lv.SmallImageList.Images.IndexOfKey(sInfo.dwAttributes.ToString()); Dictionary <Column, Column> tmp_items = new Dictionary <Column, Column>(); // fill dictionary with all values foreach (Column c in Enum.GetValues(typeof(Column))) { tmp_items.Add(c, c); } // add configured, then remove foreach (ColumnHeader header in lv.Columns) { if (header.Text == "File") { continue; } Column key = (Column)Enum.Parse(typeof(Column), header.Text); string val = GetString(key); ListViewItem.ListViewSubItem sub_item = new ListViewItem.ListViewSubItem(this, val); sub_item.Name = key.ToString(); this.SubItems.Add(sub_item); tmp_items.Remove(key); } // add the leftovers foreach (Column key in tmp_items.Keys) { if (key == Column.File) { continue; } string val = GetString(key); ListViewItem.ListViewSubItem sub_item = new ListViewItem.ListViewSubItem(this, val); sub_item.Name = key.ToString(); this.SubItems.Add(sub_item); } return(true); }
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. } }
private async void Preview(string path) { if (!File.Exists(path)) { return; } try { var tfile = TagLib.File.Create(path, TagLib.ReadStyle.None); TagLib.Id3v1.Tag t = (TagLib.Id3v1.Tag)tfile.GetTag(TagLib.TagTypes.Id3v1); TagLib.Id3v2.Tag t2 = (TagLib.Id3v2.Tag)tfile.GetTag(TagLib.TagTypes.Id3v2); ID3v1_TagList.Clear(); ID3v2_TagList.Clear(); var TagList = GetAllStringProperties(t); TagList.ForEach(x => x.Value = StringToUnicode.TryToConvertLatin1ToUnicode(x.Value, encoding[0])); var Dic = TagList.ToDictionary(x => x.TagName, x => x.Value); var resoult = ConvertEncoding ? await ConvertHelper.ConvertDictionary(Dic, encoding, ToChinese1) : await ConvertHelper.ConvertDictionary(Dic, ToChinese1); TagList.ForEach(x => { x.Value_Preview = resoult[x.TagName]; ID3v1_TagList.Add(x); }); TagList = GetAllStringProperties(t2); Dic = TagList.ToDictionary(x => x.TagName, x => { if (tfile.TagTypesOnDisk.HasFlag(TagLib.TagTypes.Id3v2)) { return(StringToUnicode.TryToConvertLatin1ToUnicode(x.Value, encoding2[0])); } else { var _ = ID3v1_TagList.Where(y => y.TagName == x.TagName).FirstOrDefault(); return(_ != null ? _.Value_Preview : ""); } }); resoult = await ConvertHelper.ConvertDictionary(Dic, ToChinese2); TagList.ForEach(x => { x.Value_Preview = resoult[x.TagName]; ID3v2_TagList.Add(x); }); } catch (TagLib.UnsupportedFormatException) { ID3v1_TagList.Clear(); ID3v2_TagList.Clear(); ID3v1_TagList.Add(new TagList_Line() { TagName = "Error", Value = "非音訊檔" }); ID3v2_TagList.Add(new TagList_Line() { TagName = "Error", Value = "非音訊檔" }); } catch (FanhuajiException val) { ID3v1_TagList.Clear(); ID3v2_TagList.Clear(); ID3v1_TagList.Add(new TagList_Line { TagName = "Error", Value = val.Message }); ID3v2_TagList.Add(new TagList_Line { TagName = "Error", Value = val.Message }); } catch (System.Exception) { ID3v1_TagList.Clear(); ID3v2_TagList.Clear(); ID3v1_TagList.Add(new TagList_Line() { TagName = "Error", Value = "未知" }); ID3v2_TagList.Add(new TagList_Line() { TagName = "Error", Value = "未知" }); } }
/// <summary> /// Adds a tag of a specified type to the current instance, /// optionally copying values from an existing type. /// </summary> /// <param name="type"> /// A <see cref="TagTypes" /> value specifying the type of /// tag to add to the current instance. At the time of this /// writing, this is limited to <see cref="TagTypes.Ape" /> /// and <see cref="TagTypes.Id3v2" />. /// </param> /// <param name="copy"> /// A <see cref="TagLib.Tag" /> to copy values from using /// <see cref="TagLib.Tag.CopyTo" />, or <see /// langword="null" /> if no tag is to be copied. /// </param> /// <returns> /// The <see cref="TagLib.Tag" /> object added to the current /// instance, or <see langword="null" /> if it couldn't be /// created. /// </returns> /// <remarks> /// ID3v2 tags are added at the end of the current instance, /// while other tags are added to the beginning. /// </remarks> public TagLib.Tag AddTag(TagTypes type, TagLib.Tag copy) { TagLib.Tag tag = null; if (type == TagTypes.Id3v2) { tag = new TagLib.Id3v2.Tag (); } else if (type == TagTypes.Ape) { tag = new TagLib.Ape.Tag (); (tag as Ape.Tag).HeaderPresent = true; } if (tag != null) { if (copy != null) copy.CopyTo (tag, true); AddTag (tag); } return tag; }
/// <summary> /// merge like values, hide unlike values /// </summary> public override void Coalesce() { FileInfo fi = (FileInfo)lv.SelectedItems[0].Tag; TagLib.File tag_file = TagLib.File.Create(fi.FullName); TagLib.Id3v2.Tag first_tag = tag_file.GetTag(TagLib.TagTypes.Id3v2) as TagLib.Id3v2.Tag; foreach (ListViewItem item in lv.SelectedItems) { fi = (FileInfo)item.Tag; tag_file = TagLib.File.Create(fi.FullName); TagLib.Tag tag = tag_file.GetTag(TagLib.TagTypes.Id3v2); if (tag != null) { if (first_tag.JoinedPerformers != tag.JoinedPerformers) { first_tag.Performers = new string[0]; } if (first_tag.Album != tag.Album) { first_tag.Album = string.Empty; } if (first_tag.Title != tag.Title) { first_tag.Title = string.Empty; } if (first_tag.Track != tag.Track) { first_tag.Track = 0; } if (first_tag.TrackCount != tag.TrackCount) { first_tag.TrackCount = 0; } if (first_tag.Disc != tag.Disc) { first_tag.Disc = 0; } if (first_tag.DiscCount != tag.DiscCount) { first_tag.DiscCount = 0; } if (first_tag.Year != tag.Year) { first_tag.Year = 0; } if (first_tag.JoinedGenres != tag.JoinedGenres) { first_tag.Genres = new string[0]; } if (first_tag.BeatsPerMinute != tag.BeatsPerMinute) { first_tag.BeatsPerMinute = 0; } if (first_tag.Comment != tag.Comment) { first_tag.Comment = string.Empty; } } } v2 = first_tag; }
/// <summary> /// Reads a tag starting at a specified position and moves the /// cursor to its start position. /// </summary> /// <param name="start"> /// A <see cref="long" /> value reference specifying at what /// position the potential tag starts. If a tag is found, /// this value will be updated to the position at which the /// found tag ends. /// </param> /// <returns> /// A <see cref="TagLib.Tag" /> object representing the tag /// found at the specified position, or <see langword="null" /// /> if no tag was found. /// </returns> private TagLib.Tag ReadTag (ref long start) { long end = start; TagTypes type = ReadTagInfo (ref end); TagLib.Tag tag = null; switch (type) { case TagTypes.Ape: tag = new TagLib.Ape.Tag (file, start); break; case TagTypes.Id3v2: tag = new TagLib.Id3v2.Tag (file, start); break; } start = end; return tag; }
public static MusicFileTag ConvertTagToMusicFileTag(TagLib.Id3v1.Tag tagV1, TagLib.Id3v2.Tag tagV2, string filePath) { var tmp = new MusicFileTag { // File Details FilePath = filePath, FileName = Path.GetFileName(filePath), FileSize = Logic.BasicFunctions.FormatFileSize(new FileInfo(filePath).Length), }; // TagTypes TagTypes myTagTypes = TagLib.File.Create(filePath).TagTypesOnDisk; tmp.EnabledV1 = myTagTypes.ToString().ToLower().Contains("id3v1") ? true : false; tmp.EnabledV2 = myTagTypes.ToString().ToLower().Contains("id3v2") ? true : false; // V1 if (tmp.EnabledV1) { tmp.ArtistV1 = tagV1.FirstPerformer == null ? "" : tagV1.FirstPerformer.Replace("�", string.Empty); tmp.AlbumV1 = tagV1.Album == null ? "" : tagV1.Album.Replace("�", string.Empty); tmp.GenreV1 = tagV1.FirstGenre == null ? "" : tagV1.FirstGenre.Replace("�", string.Empty); tmp.YearV1 = tagV1.Year.ToString() == null ? "" : tagV1.Year.ToString().Replace("�", string.Empty); tmp.TitleV1 = tagV1.Title == null ? "" : tagV1.Title.Replace("�", string.Empty); tmp.CommentV1 = tagV1.Comment == null ? "" : tagV1.Comment.Replace("�", string.Empty); tmp.TrackV1 = tagV1.Track.ToString() == null ? "" : tagV1.Track.ToString().Replace("�", string.Empty); } // V2 if (tmp.EnabledV2) { tmp.VersionV2 = tagV2.Version.ToString(); // Version 3 tmp.PlayListDelayV2 = Logic.TaggingLogic.GetTagContent(tagV2, "TDLY").Replace("�", string.Empty); tmp.TrackNumberV2 = Logic.TaggingLogic.GetTagContent(tagV2, "TRCK").Replace("�", string.Empty); tmp.PartOfSetV2 = Logic.TaggingLogic.GetTagContent(tagV2, "TPOS").Replace("�", string.Empty); tmp.BPMV2 = Logic.TaggingLogic.GetTagContent(tagV2, "TBPM").Replace("�", string.Empty); tmp.ArtistV2 = Logic.TaggingLogic.GetTagContent(tagV2, "TPE1").Replace("�", string.Empty); tmp.GenreV2 = Logic.TaggingLogic.GetTagContent(tagV2, "TCON").Replace("�", string.Empty); tmp.LanguageV2 = Logic.TaggingLogic.GetTagContent(tagV2, "TLAN").Replace("�", string.Empty); tmp.KeyV2 = Logic.TaggingLogic.GetTagContent(tagV2, "TKEY").Replace("�", string.Empty); tmp.SetSubtitleV2 = Logic.TaggingLogic.GetTagContent(tagV2, "TSST").Replace("�", string.Empty); tmp.ContentDescriptionV2 = Logic.TaggingLogic.GetTagContent(tagV2, "TIT1").Replace("�", string.Empty); tmp.InterpretedV2 = Logic.TaggingLogic.GetTagContent(tagV2, "TPE4").Replace("�", string.Empty); tmp.AlbumV2 = Logic.TaggingLogic.GetTagContent(tagV2, "TALB").Replace("�", string.Empty); tmp.TitleV2 = Logic.TaggingLogic.GetTagContent(tagV2, "TIT2").Replace("�", string.Empty); /// Frames from /// http://id3.org/id3v2.3.0#Declared_ID3v2_frames // + Version 4 if (tagV2.Version == 4) { tmp.TitleSortV2 = Logic.TaggingLogic.GetTagContent(tagV2, "TSOT").Replace("�", string.Empty); tmp.AlbumSortV2 = Logic.TaggingLogic.GetTagContent(tagV2, "TSOA").Replace("�", string.Empty); tmp.MoodV2 = Logic.TaggingLogic.GetTagContent(tagV2, "TMOO").Replace("�", string.Empty); tmp.SubtitleV2 = Logic.TaggingLogic.GetTagContent(tagV2, "TIT3").Replace("�", string.Empty); } } else { tmp.VersionV2 = "4"; } return(tmp); }
/// <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); }
private Tag GetId3Tag() { var uri = new Uri(String.Format("https://gdata.youtube.com/feeds/api/videos/{0}?v=2", _youtubeEntry.YoutubeUrl.Id)); var tag = new Tag { Title = _youtubeEntry.Title, Album = _youtubeEntry.ChannelName }; try { var xml = new XmlDocument(); var req = WebRequest.Create(uri); using (var resp = req.GetResponse()) { using (var stream = resp.GetResponseStream()) { if (stream != null) { xml.Load(stream); } } } if (xml.DocumentElement != null) { var manager = new XmlNamespaceManager(xml.NameTable); manager.AddNamespace("root", "http://www.w3.org/2005/Atom"); manager.AddNamespace("app", "http://www.w3.org/2007/app"); manager.AddNamespace("media", "http://search.yahoo.com/mrss/"); manager.AddNamespace("gd", "http://schemas.google.com/g/2005"); manager.AddNamespace("yt", "http://gdata.youtube.com/schemas/2007"); tag.Title = GetText(xml, "media:group/media:title", manager); tag.Lyrics = "MS.Video.Downloader\r\n" + GetText(xml, "media:group/media:description", manager); tag.Copyright = GetText(xml, "media:group/media:license", manager); tag.Album = _youtubeEntry.ChannelName; tag.Composers = new[] { "MS.Video.Downloader", "Youtube", GetText(xml, "root:link[@rel=\"alternate\"]/@href", manager), GetText(xml, "root:author/root:name", manager), GetText(xml, "root:author/root:uri", manager) }; var urlNodes = xml.DocumentElement.SelectNodes("media:group/media:thumbnail", manager); var webClient = new WebClient(); var pics = new List <IPicture>(); if (urlNodes != null && urlNodes.Count > 0) { foreach (XmlNode urlNode in urlNodes) { var attributes = urlNode.Attributes; if (attributes == null || attributes.Count <= 0) { continue; } var url = attributes["url"]; if (url == null || String.IsNullOrEmpty(url.Value)) { continue; } var data = webClient.DownloadData(url.Value); IPicture pic = new Picture(new ByteVector(data)); pics.Add(pic); } } tag.Pictures = pics.ToArray(); } } catch { } return(tag); }
private void ExecuteTagEdits() { if (!((SetDiscAndSetNumber && ID3V2Tag.DiscCount == 0 && (ID3V2Tag.Disc == 0 || ID3V2Tag.Disc == 1)) || (FramesToRemove != null && FramesToRemove.Any(f => !string.IsNullOrWhiteSpace(f)) && ID3V2Tag.Frames.Any(f => FramesToRemove.Contains(f.FrameId.ToString()))))) { return; } string editFile = MediaFile.FullName; if (EditAlternateFile) { if (string.IsNullOrWhiteSpace(EditFilePath)) { Logger.Info($"AlternatePath not specified in App.config file."); } editFile = editFile.Replace(ScanFilePath, EditFilePath); } TagLib.Id3v2.Tag.UseNumericGenres = false; if (File.Exists(editFile)) { if (SetDiscAndSetNumber && ID3V2Tag.DiscCount == 0 && (ID3V2Tag.Disc == 0 || ID3V2Tag.Disc == 1)) { Logger.Info($"Adding disc number and disc total."); using (TagLib.File tagFile = TagLib.File.Create(editFile)) { tagFile.Tag.Disc = 1; tagFile.Tag.DiscCount = 1; tagFile.Save(); } using (TagLib.File tagFile3 = TagLib.File.Create(editFile)) { TagLib.Id3v2.Tag v2Tag = (TagLib.Id3v2.Tag)tagFile3.GetTag(TagLib.TagTypes.Id3v2); ID3V2Tag = new TagLib.Id3v2.Tag(); v2Tag.CopyTo(ID3V2Tag, true); } } if (FramesToRemove != null && FramesToRemove.Any(f => !string.IsNullOrWhiteSpace(f)) && ID3V2Tag.Frames.Any(f => FramesToRemove.Contains(f.FrameId.ToString()))) { Logger.Info($"Removing extra frames from '{editFile}'."); DateTime editStart = DateTime.Now; try { TagLib.Tag tempTag = null; tempTag = new TagLib.Id3v2.Tag(); using (TagLib.File tagFile = TagLib.File.Create(editFile)) { TagLib.Id3v2.Tag v2Tag = (TagLib.Id3v2.Tag)tagFile.GetTag(TagLib.TagTypes.Id3v2); v2Tag.CopyTo(tempTag, true); tagFile.RemoveTags(TagLib.TagTypes.Id3v2); tagFile.Save(); } foreach (var frame in FramesToRemove.Where(f => !string.IsNullOrWhiteSpace(f))) { ((TagLib.Id3v2.Tag)tempTag).RemoveFrames(TagLib.ByteVector.FromString(frame, TagLib.StringType.UTF8)); } using (TagLib.File tagFile2 = TagLib.File.Create(editFile)) { tempTag.CopyTo(tagFile2.Tag, true); tagFile2.Save(); } using (TagLib.File tagFile3 = TagLib.File.Create(editFile)) { TagLib.Id3v2.Tag v2Tag = (TagLib.Id3v2.Tag)tagFile3.GetTag(TagLib.TagTypes.Id3v2); ID3V2Tag = new TagLib.Id3v2.Tag(); v2Tag.CopyTo(ID3V2Tag, true); } tempTag = null; } catch (Exception ex) { Logger.Error("", ex); } DateTime editEnd = DateTime.Now; if (Globals.VerboseLogging) { Logger.Info($"'{editFile}' ID3V2 tag edited in {(editEnd - editStart).TotalMilliseconds} milliseconds."); } } } else { Logger.Info($"Alternate file '{editFile}' does not exist."); } }
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}"); }); } }