private void AddFiles(string[] files) { TimeSpan startTime = new TimeSpan(); foreach (string f in files) { try { TagLib.Tag tags = TagLib.File.Create(f).Tag; int playingChannel = Bass.BASS_StreamCreateFile(f, 0, 0, 0); TimeSpan playingLength = new TimeSpan(0, 0, 0, 0, (int)(Bass.BASS_ChannelBytes2Seconds(playingChannel, Bass.BASS_ChannelGetLength(playingChannel, BASSMode.BASS_POS_BYTE)) * 1000)); int uid = UID++; audioFiles.Add(new AudioFile() { UID = uid, Tags = tags, Duration = playingLength, Location = f, StartTime = startTime }); startTime += audioFiles.Last().Duration; scrubber.TotalTime += playingLength; fileList.Items.Add(new ListViewItem(new string[] { tags.Track + "", tags.Title == null ? System.IO.Path.GetFileName(f) : tags.Title, playingLength.ToString(@"hh\:mm\:ss"), tags.Album, f }) { Name = "" + (uid), Tag = uid }); } catch { } } }
private void bOk_Click(object sender, EventArgs e) { try { TagLib.File file = TagLib.File.Create(_FileName); TagLib.Tag tags = file.Tag; tags.Title = tbTitle.Text; tags.AlbumArtists = new string[] { tbArtist.Text }; tags.Album = tbAlbum.Text; tags.Comment = tbComment.Text; tags.Genres = new string[] { tbGenre.Text }; tags.Year = (uint)int.Parse(tbYear.Text); tags.Track = (uint)int.Parse(tbTrack.Text); file.Save(); } catch (Exception ex) { #if Log Console.WriteLine(ex); #endif } this.DialogResult = DialogResult.OK; }
public TagLib.Tag AddTag(TagTypes type, TagLib.Tag copy) { TagLib.Tag tag = null; if (type == TagTypes.Id3v1) { tag = new TagLib.Id3v1.Tag(); } else if (type == TagTypes.Id3v2) { Id3v2.Tag tag32 = new Id3v2.Tag(); tag32.Version = 4; tag32.Flags |= Id3v2.HeaderFlags.FooterPresent; tag = tag32; } else if (type == TagTypes.Ape) { tag = new TagLib.Ape.Tag(); } if (tag != null) { if (copy != null) { copy.CopyTo(tag, true); } if (type == TagTypes.Id3v1) { AddTag(tag); } else { InsertTag(0, tag); } } return(tag); }
/// <summary> /// Reads a tag 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); }
private void NAudioEngine_PropertyChanged(object sender, PropertyChangedEventArgs e) { NAudioEngine engine = NAudioEngine.Instance; switch (e.PropertyName) { case "FileTag": if (engine.FileTag != null) { TagLib.Tag tag = engine.FileTag.Tag; if (tag.Title != null) { this.Title = "MusicPlayer | " + tag.Album; } if (tag.Title == null) { this.Title = "Music Player"; } if (tag.Pictures.Length > 0) { using (MemoryStream albumArtworkMemStream = new MemoryStream(tag.Pictures[0].Data.Data)) { try { BitmapImage albumImage = new BitmapImage(); albumImage.BeginInit(); albumImage.CacheOption = BitmapCacheOption.OnLoad; albumImage.StreamSource = albumArtworkMemStream; albumImage.EndInit(); albumArtPanel.AlbumArtImage = albumImage; } catch (NotSupportedException) { albumArtPanel.AlbumArtImage = null; // System.NotSupportedException: // No imaging component suitable to complete this operation was found. } albumArtworkMemStream.Close(); } } else { albumArtPanel.AlbumArtImage = null; } } else { albumArtPanel.AlbumArtImage = null; } break; case "ChannelPosition": digitalClock.Time = TimeSpan.FromSeconds(engine.ChannelPosition); break; default: // Do Nothing break; } }
private void LoadMusicFile(string filePath) { timer1.Stop(); timer1.Enabled = false; trackBar1.Value = 0; if (wo != null) { wo.Stop(); System.Threading.Thread.Sleep(100); wo.Dispose(); } if (mp3 != null) { mp3.Position = 0; mp3.CurrentTime = TimeSpan.FromSeconds(0); System.Threading.Thread.Sleep(100); mp3.Dispose(); } mp3 = new Mp3FileReader(filePath); mp3.Position = 0; wo = new WaveOut(); wo.Init(mp3); wo.Play(); tag = TagLib.File.Create(@filePath).Tag; tagfile = TagLib.File.Create(@filePath); this.Text = "YAMP - " + tag.Title + " by " + string.Join(", ", tag.Performers); label1.Text = tag.Title; label2.Text = string.Join(", ", tag.Performers); if (tag.Pictures.Length > 0) { pictureBox1.Image = Image.FromStream(new System.IO.MemoryStream(tag.Pictures[0].Data.Data)); } timer1.Start(); curFile = filePath; button2.Text = "Pause"; System.Diagnostics.Debug.WriteLine("YAMP Debug Info - " + DateTime.Now.ToString() + Environment.NewLine + "File: " + curFile + Environment.NewLine + "Audio Bitrate: " + tagfile.Properties.AudioBitrate + Environment.NewLine + "Audio Channels: " + tagfile.Properties.AudioChannels + Environment.NewLine + "Audio Sample Rate: " + tagfile.Properties.AudioSampleRate + Environment.NewLine + "Bits per Sample: " + tagfile.Properties.BitsPerSample + Environment.NewLine + "Codecs/Description: " + string.Join(", ", tagfile.Properties.Codecs) + " | " + tagfile.Properties.Description); }
public static Track ParseFromTaglib(TagLib.Tag t) { Track tag = new Track(); tag.Title = t.Title; tag.Performer = t.FirstPerformer; tag.Album = t.Album; if (t.Year > 0) { tag.Year = new DateTime(Convert.ToInt32(t.Year), 1, 1); } if (t.Pictures.Count() > 0) { MemoryStream ms = new MemoryStream(t.Pictures[0].Data.Data); BitmapImage Cover = new BitmapImage(); Cover.BeginInit(); Cover.StreamSource = ms; Cover.EndInit(); tag.AlbumArt = Cover; tag.AlbumArt.Freeze(); } //else //{ // FileStream fs = new FileStream("icon.ico", FileMode.Open); // BitmapImage Cover = new BitmapImage(); // Cover.BeginInit(); // Cover.StreamSource = fs; // Cover.EndInit(); // tag.AlbumArt = Cover; //} return(tag); }
/// <summary> /// Removes a set of tag types from the current instance. /// </summary> /// <param name="types"> /// A bitwise combined <see cref="TagLib.TagTypes" /> value /// containing tag types to be removed from the file. /// </param> /// <remarks> /// In order to remove all tags from a file, pass <see /// cref="TagTypes.AllTags" /> as <paramref name="types" />. /// </remarks> public void RemoveTags(TagTypes types) { for (int i = Tags.Length - 1; i >= 0; i--) { TagLib.Tag t = Tags [i]; if ((types & TagTypes.Id3v1) != TagTypes.None && !(t is TagLib.Id3v1.Tag)) { continue; } if ((types & TagTypes.Id3v2) != TagTypes.None && !(t is TagLib.Id3v2.Tag)) { continue; } if ((types & TagTypes.Ape) != TagTypes.None && !(t is TagLib.Ape.Tag)) { continue; } RemoveTag(t); } }
protected override void Metadata() { ResetOutBuffer(); using TagLib.File file = TagLib.File.Create(new MemoryFileAbstraction($"buffer.{MediaType.MimeToExt(MusicMime)}", OutBuffer)); TagLib.Tag tag = MusicMime switch { "audio/flac" => file.Tag, "audio/mpeg" => file.GetTag(TagLib.TagTypes.Id3v2), "audio/ogg" => file.Tag, _ => throw new FileLoadException($"Failed to get file type while processing \"{InPath}\"."), }; if (tag.Pictures.Length > 0) { tag.Pictures[0].Type = TagLib.PictureType.FrontCover; } if (ForceRename) { if (tag.Title != null && tag.AlbumArtists.Length > 0) { OutName = $"{tag.AlbumArtists[0]} - {tag.Title}"; } else if (tag.Title != null && tag.Performers.Length > 0) { OutName = $"{tag.Performers[0]} - {tag.Title}"; } else { Logger.Error("Failed to find name for {Path}", InPath); } } file.Save(); }
/// <summary> /// Reads a tag starting at a specified position and moves the /// cursor to its start position. /// </summary> /// <param name="start"> /// A <see cref="long" /> value reference specifying at what /// position the potential tag starts. If a tag is found, /// this value will be updated to the position at which the /// found tag ends. /// </param> /// <returns> /// A <see cref="TagLib.Tag" /> object representing the tag /// found at the specified position, or <see langword="null" /// /> if no tag was found. /// </returns> private TagLib.Tag ReadTag(ref long start) { long end = start; TagTypes type = ReadTagInfo(ref end); TagLib.Tag tag = null; try { switch (type) { case TagTypes.Ape: tag = new TagLib.Ape.Tag(file, start); break; case TagTypes.Id3v2: tag = new TagLib.Id3v2.Tag(file, start); break; } } catch (CorruptFileException e) { Console.Error.WriteLine("taglib-sharp caught exception creating tag: {0}", e); } start = end; return(tag); }
public TagInformation(TagLib.Tag tag) { Band = tag.FirstAlbumArtist ?? tag.FirstPerformer ?? tag.FirstComposer ?? UnknownBandName; Title = tag.Title; Track = tag.Track; Album = tag.Album ?? tag.Title; }
/// <summary> ///insert album /// </summary> /// <param name="tag">the id3 tag</param> /// <returns>primary key (insert id)</returns> private object InsertAlbum(TagLib.Tag tag) { string album = tag.Album; object album_id = null; if (album != null && album != string.Empty) { MySqlCommand cmd = new MySqlCommand(); cmd.Parameters.AddWithValue("?album", album); cmd.Parameters.AddWithValue("?artist", tag.FirstAlbumArtist); album_id = GetKey("album", "album", album); if (album_id == null) // not found { cmd.CommandText = "INSERT INTO album (album, artist) Values(?album, ?artist)"; mysql_connection.ExecuteNonQuery(cmd); album_id = mysql_connection.LastInsertID; reporter.InsertAlbumCount++; } else { cmd.Parameters.AddWithValue("?album_id", album_id); cmd.CommandText = "UPDATE album SET album=?album, artist=?artist WHERE id=?album_id"; mysql_connection.ExecuteNonQuery(cmd); reporter.UpdateAlbumCount++; } } return(album_id); }
private static void OrganizeMetadata(TagLib.Tag Tag, IEnumerable <MusicBrainz.Data.RecordingData> recordings, string Title) { Console.WriteLine("Please select the correct metadata:"); int iAux = 0; var recs = recordings.ToArray(); foreach (var recording in recs) { Console.WriteLine($"[{iAux}]:"); DisplayRecording(recording); iAux++; } Console.WriteLine($"[{iAux}]:"); Console.WriteLine($"Title: {Title}"); int iOption = GetOption(iAux); if (iOption == recs.Count()) //custom { Console.Write($"Title [{Title}]: "); string sAux = Console.ReadLine(); Tag.Title = string.IsNullOrWhiteSpace(sAux) ? Title : sAux; Console.Write("Artist: "); Tag.AlbumArtists = Tag.Performers = new string[] { Console.ReadLine() }; Console.Write("Album: "); Tag.Album = Console.ReadLine(); } else { Tag.Title = recs[iOption].Title; Tag.MusicBrainzArtistId = recs[iOption].Artistcredit.FirstOrDefault()?.Artist.Id; Tag.AlbumArtists = new string[] { recs[iOption].Artistcredit.FirstOrDefault()?.Artist.Name }; Tag.Performers = Tag.AlbumArtists; Tag.Album = recs[iOption].Releaselist.FirstOrDefault().Title; } }
public async Task MapTags(TagLib.Tag tags) { var trackNumber = GetTrackNumber(); if (trackNumber.HasValue) { tags.Track = (uint)trackNumber.Value; } tags.Title = Track.Title; tags.Subtitle = Track.TitleExtended; tags.AlbumArtists = Track.AlbumArtists ?? new[] { Track.Artist }; tags.Performers = Track.Performers ?? new[] { Track.Artist }; tags.Album = Track.Album; tags.Genres = Track.Genres; tags.Disc = (uint)(Track.Disc ?? 0); tags.Year = (uint)(Track.Year ?? 0); await FetchMediaPictures(); tags.Pictures = GetMediaPictureTag(); }
/// <summary> /// Gets a tag of a specified type from the current instance, /// optionally creating a new tag if possible. /// </summary> /// <param name="type"> /// A <see cref="TagLib.TagTypes" /> value indicating the /// type of tag to read. /// </param> /// <param name="create"> /// A <see cref="bool" /> value specifying whether or not to /// try and create the tag if one is not found. /// </param> /// <returns> /// A <see cref="Tag" /> object containing the tag that was /// found in or added to the current instance. If no /// matching tag was found and none was created, <see /// langword="null" /> is returned. /// </returns> /// <remarks> /// If a <see cref="TagLib.Id3v2.Tag" /> is added to the /// current instance, it will be placed at the start of the /// file. On the other hand, <see cref="TagLib.Id3v1.Tag" /> /// <see cref="TagLib.Ape.Tag" /> will be added to the end of /// the file. All other tag types will be ignored. /// </remarks> public override TagLib.Tag GetTag(TagTypes type, bool create) { TagLib.Tag t = (Tag as TagLib.NonContainer.Tag) .GetTag(type); if (t != null || !create) { return(t); } switch (type) { case TagTypes.Id3v1: return(EndTag.AddTag(type, Tag)); case TagTypes.Id3v2: return(StartTag.AddTag(type, Tag)); case TagTypes.Ape: return(EndTag.AddTag(type, Tag)); default: return(null); } }
public override void ThreadFunc() { foreach (FileInfo fi in infos) { OnStatusUpdate(fi.FullName); TagLib.File tag_file = TagLib.File.Create(fi.FullName); TagLib.Tag id3v1 = tag_file.GetTag(TagLib.TagTypes.Id3v1); OrganizeFormatEvaluator eval = new OrganizeFormatEvaluator(format, id3v1); string dir = String.Format("{0}\\{1}", path.TrimEnd('\\'), eval.Value.TrimStart('\\')); if (!Directory.Exists(dir)) { //TODO MessageBox() Directory.CreateDirectory(dir); } if (copy) { fi.CopyTo(dir + "\\" + fi.Name, overwrite); } else { Tools.Functions.MoveTo(fi, dir + "\\" + fi.Name, overwrite); } } // hold open for at least ... System.Threading.Thread.Sleep(1000); //SafeClose(); OnFinished(); }
/// <summary> /// /// </summary> public override void ThreadFunc() { foreach (FileInfo fi in infos) { OnStatusUpdate(fi.Name); TagLib.File tag_file = TagLib.File.Create(fi.FullName); TagLib.Tag id3v2 = tag_file.GetTag(TagLib.TagTypes.Id3v2); OrganizeFormatEvaluator eval = new OrganizeFormatEvaluator(format, id3v2); // HACK LOOK AT THIS!!! string fn = eval.Value.TrimStart('\\'); char[] chars = System.IO.Path.GetInvalidFileNameChars(); foreach (char c in chars) { fn = fn.Replace(c, '_'); } string fullname = String.Format("{0}\\{1}{2}", fi.DirectoryName, fn, fi.Extension); fi.MoveTo(fullname); //Tools.Functions.MoveTo( fi, dir.TrimEnd( '\\' ), false ); } OnStatusUpdate("Finished"); OnFinished(); // HACK!! System.Threading.Thread.Sleep(0); //SafeClose(); }
/// <summary> /// Adds a tag of a specified type to the current instance, /// optionally copying values from an existing type. /// </summary> /// <param name="type"> /// A <see cref="TagTypes" /> value specifying the type of /// tag to add to the current instance. At the time of this /// writing, this is limited to <see cref="TagTypes.Ape" /> /// and <see cref="TagTypes.Id3v2" />. /// </param> /// <param name="copy"> /// A <see cref="TagLib.Tag" /> to copy values from using /// <see cref="TagLib.Tag.CopyTo" />, or <see /// langword="null" /> if no tag is to be copied. /// </param> /// <returns> /// The <see cref="TagLib.Tag" /> object added to the current /// instance, or <see langref="null" /> if it couldn't be /// created. /// </returns> /// <remarks> /// ID3v2 tags are added at the end of the current instance, /// while other tags are added to the beginning. /// </remarks> public TagLib.Tag AddTag(TagTypes type, TagLib.Tag copy) { TagLib.Tag tag = null; if (type == TagTypes.Id3v2) { tag = new TagLib.Id3v2.Tag(); } else if (type == TagTypes.Ape) { tag = new TagLib.Ape.Tag(); (tag as Ape.Tag).HeaderPresent = true; } if (tag != null) { if (copy != null) { copy.CopyTo(tag, true); } AddTag(tag); } return(tag); }
/// <summary> /// Constructs and initializes a new instance of <see /// cref="File" /> for a specified file abstraction and /// specified read style. /// </summary> /// <param name="abstraction"> /// A <see cref="IFileAbstraction" /> object to use when /// reading from and writing to the file. /// </param> /// <param name="propertiesStyle"> /// A <see cref="ReadStyle" /> value specifying at what level /// of accuracy to read the media properties, or <see /// cref="ReadStyle.None" /> to ignore the properties. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="abstraction" /> is <see langword="null" /// />. /// </exception> /// <exception cref="CorruptFileException"> /// The file is not the write length. /// </exception> public File(File.IFileAbstraction abstraction, ReadStyle propertiesStyle) : base(abstraction) { Mode = AccessMode.Read; try { // get the pointer to the end of the tag block // and calculate the tag block length Seek(OffsetToEndTagPointer); int tagLen = ((int)ReadBlock(4).ToUInt(true)) - TagBlockOffset; // read the whole tag and send to Tag class Seek(TagBlockOffset); ByteVector bv = ReadBlock(tagLen); tag = new TagLib.Audible.Tag(bv); } finally { Mode = AccessMode.Closed; } // ?? TagTypesOnDisk = TagTypes; }
public static bool IsCoverArtLinkPresent(this Tag tag) { var comment = tag.Comment; return((!string.IsNullOrEmpty(comment) || !string.IsNullOrWhiteSpace(comment)) && (comment.StartsWith("https://media.discordapp.net/attachments/") || comment.StartsWith("https://cdn.discordapp.com/"))); }
public async Task Save() { Task <string> coverPath = DownloadAndSaveCoverAsync(); using (var file = TagLib.File.Create(fileInfo.FullName)) { file.RemoveTags(TagLib.TagTypes.Id3v1); file.RemoveTags(TagLib.TagTypes.Id3v2); TagLib.Tag tag = file.GetTag(TagLib.TagTypes.Id3v2, true); tag.Performers = Artist.Split(','); tag.Title = Title; tag.Album = Album; await coverPath; if (coverPath.Result != null) { tag.Pictures = new TagLib.IPicture[] { new TagLib.Picture(coverPath.Result) } } ; file.Save(); UpdateTimeAtOldestDate(fileInfo.FullName); } string newPath = fileInfo.DirectoryName + "\\" + ToString() + fileInfo.Extension; if (fileInfo.FullName != newPath) { fileInfo.MoveTo(newPath); } }
/// <summary> /// Save <see cref="TagLib.Tag"/> into specified separated file. /// </summary> /// <remarks> /// It is saving only tags. It won't save pictures in it. /// </remarks> /// <param name="tag"></param> /// <param name="fileName"></param> /// <param name="mimeType"></param> /// <param name="style"></param> public static void PutIntoFile(this TagLib.Tag tag, string fileName, string mimeType = "audio/mpeg", TagLib.ReadStyle style = TagLib.ReadStyle.None) { using TagLib.File tlb = TagLib.File.Create(fileName, mimeType, style); tag.CopyTo(tlb.Tag, true); tlb.Save(); }
private SongTagFile BuildSongFromTag(TagLib.Tag tag, TagLib.File track) { var song = new SongTagFile(); song.Album = tag.Album; song.Artist = tag.FirstPerformer; song.Bpm = (int?)tag.BeatsPerMinute; song.Label = tag.Publisher; song.Genre = tag.FirstGenre; song.Title = tag.Title; song.Year = (int)tag.Year; song.ImageData = tag.Pictures[0].Data.Data; song.Comment = tag.Comment; song.Country = tag.Country; song.MusicalKey = tag.TKey; song.TrackNumber = (int?)tag.Track; //Set discogs int discogsId = 0; try { discogsId = Convert.ToInt32(tag.DiscogsId); song.DiscogReleaseId = discogsId; } catch { } song.Duration = track.Properties.Duration.ToString("hh':'mm':'ss"); song.BitRate = track.Properties.AudioBitrate; return(song); }
/// <summary> /// insert album art /// </summary> /// <param name="tag">the id3 tag</param> /// <param name="current_dir">current directory</param> /// <returns>count</returns> public uint InsertArt(object song_id, TagLib.File tag_file) { string art = null; string key = null; byte[] hash = null; byte[] data = null; string type = string.Empty; string mime_type = string.Empty; string description = string.Empty; string current_dir = Path.GetDirectoryName(tag_file.Name); TagLib.Tag tag = tag_file.Tag; if (tag.Pictures.Length == 0) { return(0); } uint inserted = 0; DDLHelper helper = new DDLHelper(db); helper.DeleteArtLinks(song_id); foreach (TagLib.IPicture pic in tag.Pictures) { art = GenerateFileName(pic); data = new byte[pic.Data.Count]; pic.Data.CopyTo(data, 0); type = pic.Type.ToString(); mime_type = pic.MimeType; description = pic.Description; if (pic.MimeType != "-->") // no support for linked art { hash = ComputeHash(data); uint id = 0; key = string.Empty; if (isDuplicateInsert(hash, out id)) { string file = null; if (isOrphanedInsert(id, out file)) { // write file SaveArt(file, data); } key = id.ToString(); } else { // write file SaveArt(art, data); key = Insert(hash, art, type, description, mime_type); ++inserted; } CreateLink(song_id, key); } } return(inserted); }
private void NAudioEngine_PropertyChanged(object sender, PropertyChangedEventArgs e) { NAudioEngine engine = NAudioEngine.Instance; switch (e.PropertyName) { case "FileTag": if (engine.FileTag != null) { TagLib.Tag tag = engine.FileTag.Tag; } else { //albumArtPanel.AlbumArtImage = null; } break; case "ChannelPosition": txtTime.Text = TimeSpan.FromSeconds(engine.ChannelPosition).ToString(); break; default: // Do Nothing break; } }
/// <summary> /// Copies the values from the current instance to another /// <see cref="TagLib.Tag" />, optionally overwriting /// existing values. /// </summary> /// <param name="target"> /// A <see cref="TagLib.Tag" /> object containing the target /// tag to copy values to. /// </param> /// <param name="overwrite"> /// A <see cref="bool" /> specifying whether or not to copy /// values over existing one. /// </param> /// <remarks> /// <para>If <paramref name="target" /> is of type <see /// cref="TagLib.Ape.Tag" /> a complete copy of all values /// will be performed. Otherwise, only standard values will /// be copied.</para> /// </remarks> /// <exception cref="ArgumentNullException"> /// <paramref name="target" /> is <see langword="null" />. /// </exception> public override void CopyTo(TagLib.Tag target, bool overwrite) { if (target == null) { throw new ArgumentNullException("target"); } TagLib.Ape.Tag match = target as TagLib.Ape.Tag; if (match == null) { base.CopyTo(target, overwrite); return; } foreach (Item item in items) { if (!overwrite && match.GetItem(item.Key) != null) { continue; } match.items.Add(item.Clone()); } }
private void SetProperties(TagLib.Tag tag) { genre = tag.FirstGenre; if (string.IsNullOrWhiteSpace(genre)) { genre = null; } if (tag.Track != 0 && tag.Track < (1 << 10)) { track = (int)tag.Track; } title = tag.Title; if (string.IsNullOrWhiteSpace(title)) { title = null; } description = tag.Comment; if (string.IsNullOrWhiteSpace(description)) { description = null; } if (string.IsNullOrWhiteSpace(artist)) { performer = tag.JoinedPerformers; } else { performer = tag.JoinedPerformersSort; } if (string.IsNullOrWhiteSpace(performer)) { performer = null; } artist = tag.JoinedAlbumArtists; if (string.IsNullOrWhiteSpace(artist)) { artist = tag.JoinedComposers; } if (string.IsNullOrWhiteSpace(artist)) { artist = null; } album = tag.AlbumSort; if (string.IsNullOrWhiteSpace(album)) { album = tag.Album; } if (string.IsNullOrWhiteSpace(album)) { album = null; } }
private static string GetArtist(TagLib.Tag tag) { #pragma warning disable 618 return(tag.JoinedAlbumArtists ?? tag.JoinedArtists ?? tag.JoinedPerformers ?? tag.JoinedComposers ?? "Unknown"); #pragma warning restore 618 }
/// <summary> /// Updates the track with the properties of the given file /// </summary> /// <param name="file">The file to update to</param> public void Update(FileInfo file) { // Set the Uri this.Uri = new Uri(file.FullName); // Get the tag for the file TagLib.Tag tag = null; TagLib.File tagFile = null; try { tagFile = TagLib.File.Create(file.FullName); tag = tagFile.Tag; } catch (Exception) { Log("Could not parse tags for file " + file.FullName); } // Set properties if we have a tag if (tagFile != null) { this.TitleSort = tag.TitleSort; this.Title = tag.Title; this.ArtistSort = tag.JoinedPerformersSort; this.Artist = tag.JoinedPerformers; this.AlbumSort = tag.AlbumSort; this.Album = tag.Album; this.AlbumArtistSort = String.Join(Util.NullSortValue, tag.AlbumArtistsSort); this.AlbumArtist = tag.JoinedAlbumArtists; this.Genre = tag.JoinedGenres.ToTitleCase(); this.DiscNumber = tag.Disc; this.Duration = tagFile.Properties.Duration; this.TrackNumber = tag.Track; this.Year = tag.Year; } // Retrieve title and artist from filename if not set bool hasTitle = !String.IsNullOrEmpty(this.Title), hasArtist = !String.IsNullOrEmpty(this.Artist); if (!hasTitle || !hasArtist) { var name = Path.GetFileNameWithoutExtension(file.Name); var hyphenIndex = name.IndexOf('-'); if (!hasTitle) { this.Title = (hyphenIndex == -1 ? name : name.Substring(hyphenIndex + 1)).Trim(); } if (!hasArtist) { this.Artist = hyphenIndex == -1 ? null : name.Substring(0, hyphenIndex).Trim(); } } }
private void playSong() { while (!isStopped) { isMusicEnd = false; TagLib.File songFile = TagLib.File.Create(SongFiles[CurrentSong]); currentSongFileDescriptor = songFile.Tag; if (currentSongFileDescriptor.Pictures.Length > 0) { foreach (var pic in currentSongFileDescriptor.Pictures) { OnSongPicLoaded?.Invoke(pic.Data.Data); break; } } else { OnSongPicLoaded?.Invoke(null); } songFile.Dispose(); // 这个bug是当前第一优先级 try { audioFile = new AudioFileReader(SongFiles[CurrentSong]); } catch (Exception ex) { CurrentSong = (CurrentSong + 1) % SongFiles.Count; continue; } SampleAggregator aggregator = new SampleAggregator(audioFile) { NotificationCount = audioFile.WaveFormat.SampleRate / 1024, PerformFFT = true, }; aggregator.FFTCalculated += Aggregator_FFTCalculated; aggregator.MaximumCalculated += Aggregator_MaximumCalculated; playAction?.Invoke(); outputDevice.Stop(); outputDevice.Init(aggregator); outputDevice.Play(); while (!Main.gameMenu && !isMusicEnd && (outputDevice.PlaybackState == PlaybackState.Playing || outputDevice.PlaybackState == PlaybackState.Paused)) { Thread.Sleep(16); OnProgressUpdate(audioFile.CurrentTime, audioFile.TotalTime); } if (Main.gameMenu || isStopped) { break; } CurrentSong = (CurrentSong + 1) % SongFiles.Count; playAction = null; } }
/// <summary> /// Constructs and initializes a new instance of <see /// cref="File" /> for a specified file abstraction and /// specified read style. /// </summary> /// <param name="abstraction"> /// A <see cref="IFileAbstraction" /> object to use when /// reading from and writing to the file. /// </param> /// <param name="propertiesStyle"> /// A <see cref="ReadStyle" /> value specifying at what level /// of accuracy to read the media properties, or <see /// cref="ReadStyle.None" /> to ignore the properties. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="abstraction" /> is <see langword="null" /// />. /// </exception> /// <exception cref="CorruptFileException"> /// The file is not the write length. /// </exception> public File (File.IFileAbstraction abstraction, ReadStyle propertiesStyle) : base (abstraction) { Mode = AccessMode.Read; try { // get the pointer to the end of the tag block // and calculate the tag block length Seek (OffsetToEndTagPointer); int tagLen = ( (int) ReadBlock(4).ToUInt(true) ) - TagBlockOffset; // read the whole tag and send to Tag class Seek (TagBlockOffset); ByteVector bv = ReadBlock(tagLen); tag = new TagLib.Audible.Tag( bv ); } finally { Mode = AccessMode.Closed; } // ?? TagTypesOnDisk = TagTypes; }