protected override Id3Tag[] GetTagInfo(Id3Tag tag) { const string SearchLyricsUrlFormat = "http://webservices.lyrdb.com/lookup.php?q={0}|{1}&for=match&agent=ID3.NET/1.0"; const string RetrieveLyricsUrlFormat = "http://webservices.lyrdb.com/getlyr.php?q={0}"; string searchResult = GetWebResponse(SearchLyricsUrlFormat, Utility.UrlEncode(tag.Artists.Value[0]), Utility.UrlEncode(tag.Title.Value)); if (string.IsNullOrEmpty(searchResult)) { return(Id3Tag.Empty); } string[] lineParts = searchResult.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); string id = lineParts[0]; if (string.IsNullOrEmpty(id)) { return(Id3Tag.Empty); } string lyricsResult = GetWebResponse(RetrieveLyricsUrlFormat, id); string lyrics = lyricsResult.Replace("\x000D\x000A", Environment.NewLine).Replace("\x000A", Environment.NewLine); var result = new Id3Tag(); result.Lyrics.Add(new LyricsFrame { Lyrics = lyrics }); return(new[] { result }); }
public void Write(Mp3MetaData mp3MetaData, string inputFilePath) { using (var fileStream = new FileStream(inputFilePath, FileMode.Open)) { using (var mp3 = new Mp3Stream(fileStream, Mp3Permissions.ReadWrite)) { mp3.DeleteAllTags(); // make sure the file got no tags var id3Tag = new Id3Tag(); id3Tag.Title.Value = mp3MetaData.Title; foreach (var artist in mp3MetaData.Artists) { id3Tag.Artists.Value.Add(artist); } id3Tag.Album.Value = mp3MetaData.Album; id3Tag.Year.Value = mp3MetaData.Year; id3Tag.Pictures.Add(new PictureFrame() { PictureType = PictureType.FrontCover, PictureData = mp3MetaData.Cover }); mp3.WriteTag(id3Tag, 2, 3); } } }
public void ImportPaths(params string[] paths) { if (paths.Any(p => checkExtension(Path.GetExtension(p)))) { return; } foreach (string p in paths) { AudioMetadata meta = new AudioMetadata(); using (var mp3 = new Mp3(p)) { Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2X); if (tag.CustomTexts.Count > 0 && tag.CustomTexts.Any(t => t.Value.StartsWith("DISPLAY ARTIST\0"))) { meta.Artist = meta.ArtistUnicode = tag.CustomTexts.First(t => t.Value.StartsWith("DISPLAY ARTIST\0")).Value.Split("DISPLAY ARTIST\0")[1]; } else if (tag.Artists.Value.Count > 0) { meta.Artist = meta.ArtistUnicode = tag.Artists.Value[0]; } else { meta.Artist = meta.ArtistUnicode = "Unkown Artist"; } meta.Title = meta.TitleUnicode = tag.Title.Value ?? "Unkown Title"; } playlist.AddSong(meta, p); } }
private byte[] GetTagBytes(Id3Tag tag) { var bytes = new List <byte>(); bytes.AddRange(AsciiEncoding.GetBytes("ID3")); bytes.AddRange(new byte[] { 3, 0, 0 }); foreach (Id3Frame frame in tag.Frames) { if (frame.IsAssigned) { FrameHandler mapping = FrameHandlers[frame.GetType()]; if (mapping != null) { byte[] frameBytes = mapping.Encoder(frame); bytes.AddRange(AsciiEncoding.GetBytes(GetFrameIdFromFrame(frame))); bytes.AddRange(SyncSafeNumber.EncodeNormal(frameBytes.Length)); bytes.AddRange(new byte[] { 0, 0 }); bytes.AddRange(frameBytes); } } } int framesSize = bytes.Count - 6; bytes.InsertRange(6, SyncSafeNumber.EncodeSafe(framesSize)); return(bytes.ToArray()); }
public async Task <Id3Tag> GetId3TagAsync(File file) { var id3Tag = new Id3Tag(); try { await Task.Run(() => { using (var fileStream = new FileStream(file.Path, FileMode.OpenOrCreate)) { var tagFile = TagLib.File.Create(new StreamFileAbstraction(file.Name, fileStream, fileStream)); var tags = tagFile.GetTag(TagTypes.Id3v2); id3Tag.Artist = string.IsNullOrEmpty(tags.FirstPerformer) ? tags.FirstAlbumArtist : tags.FirstPerformer; id3Tag.Title = tags.Title; id3Tag.Album = tags.Album; id3Tag.Genre = tags.FirstGenre; id3Tag.Year = tags.Year.ToString(); id3Tag.TrackNumber = tags.Track.ToString(); var picture = tags.Pictures[0]; id3Tag.AlbumArt = ImageSource.FromStream(() => GetImageMemoryStream(picture)); } }); } catch (Exception ex) { Console.WriteLine(ex); } return(await Task.FromResult(id3Tag)); }
private static void GetLabelPublisher(SongTagFile song, Id3Tag tag) { if (tag.Publisher.IsAssigned) { song.Label = tag.Publisher.Value.CleanString(); } }
public static void ReadTagToID3(Id3Tag id3, string filename) { ProcessStartInfo processinfo = new ProcessStartInfo(); string tagfile = Path.Combine(Application.StartupPath, "tools\\tag.exe"); processinfo.FileName = tagfile; processinfo.Arguments = "\"" + filename + "\" --stdout"; processinfo.UseShellExecute = false; //输出信息重定向 processinfo.CreateNoWindow = true; processinfo.RedirectStandardInput = true; processinfo.RedirectStandardOutput = true; processinfo.RedirectStandardError = false; processinfo.WindowStyle = ProcessWindowStyle.Hidden; Process tag = new Process(); tag.StartInfo = processinfo; tag.Start(); var result = tag.StandardOutput.ReadToEnd(); id3.Title.Value = GetValueByText(result, "Title"); id3.Artists.Value = GetValueByText(result, "Artist"); id3.Track.Value = GetValueByText(result, "Track"); id3.Genre.Value = GetValueByText(result, "Genre"); id3.Year.Value = GetValueByText(result, "Year"); Id3.Frames.CommentFrame c = new Id3.Frames.CommentFrame(); c.Comment = GetValueByText(result, "Comment"); id3.Comments.Add(c); }
private static void EditFile(string fileName) { Console.WriteLine(fileName); var dados = Path.GetFileNameWithoutExtension(fileName); if (dados.IndexOf("-") == -1) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(" Above file was ignored, isn't the match pattern Artist - Title."); Console.ResetColor(); return; } using (var mp3 = new Mp3(fileName, Mp3Permissions.ReadWrite)) { mp3.DeleteAllTags(); var tag = new Id3Tag(); var propinfo = typeof(Id3Tag).GetProperty("Version", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); propinfo.SetValue(tag, Id3Version.V23); tag.Artists.Value.Clear(); tag.Artists.Value.Add(dados.Substring(0, dados.IndexOf("-") - 1).Trim()); tag.Title.Value = dados.Substring(dados.IndexOf("-") + 1, dados.Length - (dados.IndexOf("-") + 1)).Trim(); mp3.WriteTag(tag, WriteConflictAction.Replace); } }
public bool Read(Id3Tag tag, Stream mp3Stream) { //Check wether the file contains an Id3v1 tag-------------------------------- mp3Stream.Seek( -128 , SeekOrigin.End); byte[] b = new byte[3]; mp3Stream.Read( b, 0, 3 ); mp3Stream.Seek(0, SeekOrigin.Begin); string tagS = Encoding.ASCII.GetString(b); if(tagS != "TAG") return false; mp3Stream.Seek( - 128 + 3, SeekOrigin.End ); //Parse the tag -)------------------------------------------------ tag.AddTitle(Read(mp3Stream, 30)); tag.AddArtist(Read(mp3Stream, 30)); tag.AddAlbum(Read(mp3Stream, 30)); //------------------------------------------------ tag.AddYear(Read(mp3Stream, 4)); tag.AddComment(Read(mp3Stream, 30)); //string trackNumber; mp3Stream.Seek(- 2, SeekOrigin.Current); b = new byte[2]; mp3Stream.Read(b, 0, 2); if (b[0] == 0) tag.AddTrack(b[1].ToString()); byte genreByte = (byte) mp3Stream.ReadByte(); mp3Stream.Seek(0, SeekOrigin.Begin); tag.AddGenre(TagGenres.Get(genreByte)); return true; }
public Id3Tag[] GetInfo(Id3Tag tag, InfoProviderInputs inputs) { try { _inputs = inputs ?? InfoProviderInputs.Default; if (!MeetsInputCriteria(tag)) { throw new InfoProviderException("Required inputs do not exist in the tag parameter"); } Id3Tag[] result = GetTagInfo(tag); return(result); } catch (InfoProviderException) { throw; } catch (TargetInvocationException ex) { throw new InfoProviderException(ex.InnerException.Message, ex.InnerException); } catch (Exception ex) { throw new InfoProviderException(ex.Message, ex); } }
private void lblAnswer_Click(object sender, EventArgs e) { var mp3 = new Mp3(Victorina.answer); Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2X); lblAnswer.Text = tag.Artists + " - " + tag.Title; }
private void ScanRepo(DirectoryInfo dir) { // Check if path exists and we can access the directory if (!dir.Exists) { return; } // walk through the files foreach (FileInfo file in dir.EnumerateFiles()) { using (var mp3 = new Mp3File(file)) { Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2x); Track track = new Track() { Title = tag.Title, Album = new Album(tag.Album), Artist = new Artist(tag.Artists), Repository = _currentRepo, RelativePath = _currentRepoUri.MakeRelativeUri(new Uri(file.FullName)).ToString() }; } //using (VisionServerContext db = new VisionServerContext()) //{ // db.Tracks.AddAsync(track); //} } // walk through the directories }
public IReadOnlyDictionary <string, string> ReadTags(string filePath) { var tags = new Dictionary <String, String>(); if (!filePath.EndsWith(".mp3")) { throw new UnsupportedFileFormatException("Unsupported file format. Must be .mp3"); } using (var mp3 = new Mp3File(filePath)) { Id3Tag tag = mp3.GetTag(Id3TagFamily.FileStartTag); tags.Add("Album", tag.Album.Value); tags["Artist"] = tag.Artists.Value; StringBuilder sb = new StringBuilder(); foreach (var value in tag.Comments) { sb.AppendLine(value.Comment); } tags["Comments"] = sb.ToString(); tags["TrackNo"] = tag.Track.Value; tags["DateReleased"] = tag.Year.Value; } return(tags.ToImmutableDictionary()); }
private void StartButton_Click(object sender, RoutedEventArgs e) { string startFolder = @"C:\Users\ppras_000\Desktop\Creating Lasting Change"; DirectoryInfo di = new DirectoryInfo(startFolder); foreach (var dir in di.GetDirectories()) { foreach (var file in dir.GetFiles("*.mp3")) { using (FileStream fs = new FileStream(file.FullName, FileMode.Open)) { using (var mp3 = new Mp3Stream(fs, Mp3Permissions.ReadWrite)) { Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2x); tag.Title.Value = file.Name.Substring(0, 2); tag.Album.Value = dir.Name.Substring(0, 6); mp3.WriteTag(tag); } } } } MessageBox.Show("Done"); }
public void SerializationTest() { SoapFormatter f = new SoapFormatter().IncludeId3SerializationSupport(); var tag = new Id3Tag(); tag.BeatsPerMinute.Value = 3; tag.Artists.Value.Add("The artist"); tag.Album.Value = "The album name"; tag.Track.Value = 5; byte[] serialized; using (var ms = new MemoryStream()) { f.Serialize(ms, tag); ms.Flush(); serialized = ms.ToArray(); } using (var ms = new MemoryStream(serialized)) { var deserialized = (Id3Tag)f.Deserialize(ms); Assert.NotNull(deserialized); } }
/// <summary> /// Generates a m3u file with all mp3 files in the specified directory /// </summary> /// <param name="mp3Directory"></param> /// <param name="m3uName">The optional name of the m3u file. If not specified, the name of the directory containing the mp3 files is used.</param> /// <param name="m3uDirectory">The optional directory where the m3u file is created. If not specified, the m3u file is created in the directory containing the mp3 files.</param> public void CreateM3u(string mp3Directory, string m3uName = null, string m3uDirectory = null) { var directoryInfo = new DirectoryInfo(mp3Directory); string m3uFilename = String.IsNullOrEmpty(m3uName) ? directoryInfo.Name : m3uName; m3uFilename = Path.ChangeExtension(m3uFilename, ".m3u"); string m3uDirectoryName = String.IsNullOrEmpty(m3uDirectory) ? mp3Directory : m3uDirectory; Directory.CreateDirectory(m3uDirectoryName); string m3uFile = Path.Combine(m3uDirectoryName, m3uFilename); using (var m3u = new StreamWriter(m3uFile, false)) { m3u.WriteLine("#EXTM3U"); foreach (string mp3File in Directory.EnumerateFiles(mp3Directory, "*.mp3", SearchOption.AllDirectories)) { String mp3FileRelative = Path.GetRelativePath(m3uDirectoryName, mp3File); using (var mp3 = new Mp3(mp3File)) { Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2X); m3u.WriteLine($"#EXTINF:{tag.Length.Value.TotalSeconds:F0},{tag.Artists.Value.FirstOrDefault() ?? ""} - {tag.Title}"); m3u.WriteLine(mp3FileRelative); } } } }
private static void GetGenre(SongTagFile song, Id3Tag tag) { if (tag.Genre.IsAssigned) { song.Genre = tag.Genre.Value.CleanString(); } }
public static void SetFileTags(Mp3File file, Mp3Tag data) { if (data != null) { using (var mp3 = new Mp3(file.FilePath, Mp3Permissions.ReadWrite)) { Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2X); if (tag == null) { tag = new Id3Tag(); var propinfo = typeof(Id3Tag).GetProperty("Version", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); propinfo.SetValue(tag, Id3Version.V23); } tag.Artists.Value.Add(data.Artist); tag.Title = new TitleFrame(data.Title); tag.Album = new AlbumFrame(data.Album); tag.Year = new YearFrame(data.Year); if (tag.Genre.Value != null) { string filteredGenre = string.Join(';', tag.Genre.Value.Split(';').Where(x => FilterGenre(x))); tag.Genre = new GenreFrame(filteredGenre); } mp3.WriteTag(tag, WriteConflictAction.Replace); file.Filled = true; Console.WriteLine($"{data.Artist}\t{data.Title}\t{data.Album}\t{data.Year}\t{data.Genres}"); } } }
private static void GetArtist(SongTagFile song, Id3Tag tag) { if (tag.Artists.IsAssigned) { song.Artist = tag.Artists.Value.CleanString(); } }
public void DevTests() { using (var mp3 = new Mp3File(@"E:\Temp\Audio\BasicTagsWithImage.mp3", Mp3Permissions.ReadWrite)) { mp3.DeleteAllTags(); var tag = new Id3Tag(); var frontCover = new PictureFrame { Description = "The Front Cover", MimeType = "image/jpg", PictureType = PictureType.FrontCover }; frontCover.LoadImage(@"E:\Temp\Audio\FrontCover.jpg"); tag.Pictures.Add(frontCover); var fileIcon = new PictureFrame { Description = "The File Icon", MimeType = "image/png", PictureType = PictureType.Other }; fileIcon.LoadImage(@"E:\Temp\Audio\MSN.png"); tag.Pictures.Add(fileIcon); mp3.WriteTag(tag); foreach (Id3Frame frame in tag) { Console.WriteLine(frame); } } }
private static void GetComments(SongTagFile song, Id3Tag tag) { //Get comment from list if (tag.Comments.Count > 0) { song.Comment = tag.Comments[0].Comment.CleanString(); } }
private static void GetAlbum(SongTagFile song, Id3Tag tag) { //set standard issue props if (tag.Album.IsAssigned) { song.Album = tag.Album.Value.CleanString(); } }
private static void GetYear(SongTagFile song, Id3Tag tag) { //Get year from DateTime if (tag.Year.AsDateTime.HasValue) { song.Year = tag.Year.AsDateTime.HasValue ? tag.Year.AsDateTime.Value.Year : 0; } }
public void StubHandlerTests() { using (var mp3 = new Mp3File(@"E:\Temp\Abba - Fernando.mp3")) { Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2x); Console.WriteLine("{0}.{1}", tag.MajorVersion, tag.MinorVersion); } }
private static void GetPictureBytes(SongTagFile song, Id3Tag tag) { //Extract the picture to bytes. if (tag.Pictures?.Count > 0) { song.ImageData = tag.Pictures[0].PictureData; } }
private void GetDiscogsId(SongTagFile song, Id3Tag tag) { long discogId = GetDiscogId(tag).ReleaseId; if (discogId > 0) { song.DiscogReleaseId = (int)discogId; } }
private void AddId3Frame(Id3Tag tag, string field, byte[] b, byte version) { if (version == Id3Tag.ID3V22) { field = ConvertFromId3v22(field); } if (field == "" || field.Length < 4) { return; } //FIXME: We do not support non-text frames yet. if (field != "COMM" && (field[0] != 'T' || field[1] == 'X')) { return; } if (field == "COMM") { TextId3Frame f = new CommId3Frame(b, version); tag.AddComment(f.Content); } else if (field[0] == 'T' && field[1] != 'X') { /* * FIXME: Add support for: they have a special format * if (field.equalsIgnoreCase("TDRC")) { * return new TimeId3Frame(field, data, version); * } * return new TextId3Frame(field, data, version); */ TextId3Frame f = new TextId3Frame(field, b, version); switch (field) { case "TCON": // genre tag.AddGenre(TranslateGenre(f.Content)); break; case "TRCK": // track number string num, count; Utils.SplitTrackNumber(f.Content, out num, out count); if (num != null) { tag.AddTrack(num); } if (count != null) { tag.AddTrackCount(count); } break; default: tag.Add(field, f.Content); break; } } }
private string GetNewName(Id3Tag tag, string originalName, out string missingFrameName) { missingFrameName = null; string missingFrame = null; //Make two passes of the patterns. //In the first pass, we try to find the perfect match without resorting to the //ResolveMissingData event. //If we still don't have a match, in the second pass, we use the ResolveMissingData event. for (var i = 0; i < 2; i++) { foreach (string pattern in _patterns) { var hasMissingFrames = false; int iteration = i; string newName = FramePlaceholderPattern.Replace(pattern, match => { //If this pattern already has missing frames, don't proces anything if (hasMissingFrames) { return(string.Empty); } string frameName = match.Groups[1].Value; PropertyInfo frameProperty = _mapping[frameName]; //Because all frame properties in Id3Tag are lazily-loaded, this will never be null var frame = (Id3Frame)frameProperty.GetValue(tag, null); if (frame.IsAssigned) { return(frame.ToString()); } if (iteration == 1) { string frameValue = FireResolveMissingDataEvent(tag, frame, originalName); if (!string.IsNullOrWhiteSpace(frameValue)) { return(frameValue); } } hasMissingFrames = true; missingFrame = frameName; return(string.Empty); }); if (!hasMissingFrames) { return(newName); } } } missingFrameName = missingFrame; return(null); }
public void Init(string file, IOutput output) { _output = output; _file = file; using (var mp3 = new Mp3(file, Mp3Permissions.Read)) { _tag = mp3.GetTag(Id3TagFamily.Version2X); } _encoding = (_tag.Version == Id3Version.V23 || _tag.Version == Id3Version.V1X) ? Id3TextEncoding.Unicode : (Id3TextEncoding)03;//TODO: Should be changed to utf-8 when implemented }
public Mp3Tag(Id3Tag tag) { this.tag = tag; Artist = string.Join(';', tag.Artists.Value); Title = tag.Title.Value; Album = tag.Album.Value; Year = Convert.ToInt32(tag.Year.Value); Genres = tag.Genre.Value; }
public void Init(string file, IOutput output) { _output = output; _file = file; using (var mp3 = new Mp3File(file, Mp3Permissions.Read)) { _tag = mp3.GetTag(Id3TagFamily.Version2x); } _encoding = _tag.MinorVersion == 4 ? (Id3TextEncoding)03 : Id3TextEncoding.Unicode;//TODO: Should be changed to utf-8 when implemented }
private static string GetAlbum(Id3Tag tag, StreamWriter log, string file) { if (tag.Album != null && tag.Album.IsAssigned && !string.IsNullOrWhiteSpace(tag.Album.Value) && tag.Album.Value.Any(c => c != '\0')) { return FixName(tag.Album.Value); } else { log.WriteLine("Unknown album for file '{0}'", file); return "Unknown Album"; } }
public bool Read(Id3Tag tag, Stream mp3Stream) { byte[] b = new byte[3]; mp3Stream.Read(b, 0, b.Length); mp3Stream.Seek(0, SeekOrigin.Begin); string ID3 = Encoding.ASCII.GetString(b); if (ID3 != "ID3") return false; //Begins tag parsing --------------------------------------------- mp3Stream.Seek(3, SeekOrigin.Begin); // ID3v2.xx.xx string versionHigh=mp3Stream.ReadByte() +""; mp3Stream.ReadByte(); //string versionID3 =versionHigh+ "." + mp3Stream.ReadByte(); //Tag Header Flags this.ID3Flags = ProcessID3Flags( (byte) mp3Stream.ReadByte() ); // Tag Length from the header b = new byte[4]; mp3Stream.Read(b, 0, b.Length); int tagSize = Utils.ReadSyncsafeInteger(b); //Fill a byte buffer, then process according to correct version b = new byte[tagSize+2]; mp3Stream.Read(b, 0, b.Length); ByteBuffer bb = new ByteBuffer(b); if (ID3Flags[0]==true) { //We have unsynchronization, first re-synchronize bb = synchronizer.synchronize(bb); } if (versionHigh == "2") v24.Read(tag, bb, ID3Flags, Id3Tag.ID3V22); else if (versionHigh == "3") v24.Read(tag, bb, ID3Flags, Id3Tag.ID3V23); else if (versionHigh == "4") v24.Read(tag, bb, ID3Flags, Id3Tag.ID3V24); else return false; return true; }
public void initialize(Song song) { if (song.usingTagLib) { metaFile = song.tagFile; this.Text = song.ToString(); textBox_Title.Text = metaFile.Tag.Title; textBox_Artist.Text = metaFile.Tag.FirstPerformer; if (metaFile.Tag.Genres.Length > 0) textBox_Genre.Text = metaFile.Tag.Genres[0]; foreach (String genre in metaFile.Tag.Genres) textBox_Genre.Text += "; " + genre; textBox_Album.Text = metaFile.Tag.Album; textBox_Year.Text = "" + metaFile.Tag.Year; textBox_Comments.Text = metaFile.Tag.Comment; button_SaveChanges.Enabled = true; } else if (song.usingId3Tag && !song.fileCorrupted) { id3Tag = song.id3Tag; this.Text = song.ToString(); textBox_Title.Text = id3Tag.Title.Value; textBox_Artist.Text = id3Tag.Artists.Value; textBox_Genre.Text = id3Tag.Genre.Value; textBox_Album.Text = id3Tag.Album.Value; textBox_Year.Text = "" + id3Tag.Year.Value; foreach (CommentFrame comment in id3Tag.Comments) textBox_Comments.Text += comment.Comment + "\n"; button_SaveChanges.Enabled = true; } else { //initialized = false; textBox_Title.Text = null; textBox_Artist.Text = null; textBox_Genre.Text = null; textBox_Album.Text = null; textBox_Year.Text = null; textBox_Comments.Text = null; button_SaveChanges.Enabled = false; } }
private static string GetArtist(Id3Tag tag, StreamWriter log, string file) { if (tag.Band != null && tag.Band.IsAssigned && !string.IsNullOrWhiteSpace(tag.Band.Value)) { tag.Band.Value = FixName(tag.Band.Value); return tag.Band.Value; } else if (tag.Artists != null && tag.Artists.IsAssigned && !string.IsNullOrWhiteSpace(tag.Artists.Value)) { tag.Artists.Value = FixName(tag.Artists.Value); tag.Band.Value = tag.Artists.Value; return tag.Artists.Value; } else { log.WriteLine("Unknown artist for file '{0}'", file); return "Unknown Artist"; } }
public bool initialize(String file) { filepath = file; int startpos = filepath.LastIndexOf("\\"); if (startpos == -1) startpos = filepath.LastIndexOf("/"); if (startpos == -1) startpos = 0; filename = filepath.Substring(startpos + 1, filepath.Length - startpos - 5); try { tagFile = File.Create(filepath); usingTagLib = true; return true; } catch (Exception ex) { Debug.WriteLine(filepath + " invalid. Trying ID3."); //Debug.WriteLine(ex.Message); usingTagLib = false; } try { using (Mp3File mp3 = new Mp3File(filepath, Mp3Permissions.ReadWrite)) { id3Tag = mp3.GetTag(Id3TagFamily.FileStartTag); try { if (!String.IsNullOrWhiteSpace(id3Tag.Artists.Value) && !String.IsNullOrWhiteSpace(id3Tag.Title.Value)) { usingId3Tag = true; return true; } } catch (Exception ex) { Debug.WriteLine("Could not load ID3v2. Attempting v1"); } try { id3Tag = mp3.GetTag(Id3TagFamily.FileEndTag); Debug.WriteLine("trying v1"); if (!String.IsNullOrWhiteSpace(id3Tag.Artists.Value) && !String.IsNullOrWhiteSpace(id3Tag.Title.Value)) { usingId3Tag = true; return true; } } catch (Exception ex) { Debug.WriteLine("Could not load v1!!!"); fileCorrupted = true; } } } catch (Exception ex) { Debug.WriteLine("Problem with mp3. Likely Problem: incorrect filepath or name."); fileCorrupted = true; } return false; }
private static string GetTitle(Id3Tag tag, StreamWriter log, string file) { if (tag.Title != null && tag.Title.IsAssigned && !string.IsNullOrWhiteSpace(tag.Title.Value)) { return FixName(tag.Title.Value).Trim(); } else { log.WriteLine("Unknown title for file '{0}'", file); return "Unknown Title"; } }
private void AddId3Frame(Id3Tag tag, string field, byte[] b, byte version) { if(version == Id3Tag.ID3V22) field = ConvertFromId3v22(field); if (field == "" || field.Length < 4) return; //FIXME: We do not support non-text frames yet. if (field != "COMM" && (field[0] != 'T' || field[1] == 'X')) return; if (field == "COMM") { TextId3Frame f = new CommId3Frame(b, version); tag.AddComment(f.Content); } else if (field[0] == 'T' && field[1] != 'X') { /* FIXME: Add support for: they have a special format if (field.equalsIgnoreCase("TDRC")) { return new TimeId3Frame(field, data, version); } return new TextId3Frame(field, data, version); */ TextId3Frame f = new TextId3Frame(field, b, version); switch (field) { case "TCON": // genre tag.AddGenre(TranslateGenre(f.Content)); break; case "TRCK": // track number string num, count; Utils.SplitTrackNumber(f.Content, out num, out count); if (num != null) tag.AddTrack(num); if (count != null) tag.AddTrackCount(count); break; default: tag.Add(field, f.Content); break; } } }
public void Read(Id3Tag tag, ByteBuffer data, bool[] ID3Flags, byte version) { // get the tagsize from the buffers size. int tagSize = data.Limit; byte[] b; // Create a result object // Id3v2Tag tag = new Id3v2Tag(); // --------------------------------------------------------------------- // If the flags indicate an extended header to be present, read its // size and skip it. (It does not contain any useful information, maybe // CRC) if ((version == Id3Tag.ID3V23 || version == Id3Tag.ID3V24) && ID3Flags[1]) ProcessExtendedHeader(data, version); //---------------------------------------------------------------------------- /* * Now start the extraction of the text frames. */ // The frame names differ in lengths between version 2 to 3 int specSize = (version == Id3Tag.ID3V22) ? 3 : 4; // As long as we have unread bytes... for (int a = 0; a < tagSize; a++) { // Create buffer taking the name of the frame. b = new byte[specSize]; // Do we still have enough bytes for reading the name? if(data.Remaining <= specSize) break; // Read the Name data.Get(b); // Convert the bytes (of the name) into a String. string field = Encoding.ASCII.GetString(b); // If byte[0] is zero, we have invalid data if (b[0] == 0) break; // Now we read the length of the current frame int frameSize = ReadInteger(data, version); // If the framesize is greater than the bytes we've left to read, // or the frame length is zero, abort. Invalid data if ((frameSize > data.Remaining) || frameSize <= 0) //Ignore empty frames break; b = new byte[frameSize + ((version == Id3Tag.ID3V23 || version == Id3Tag.ID3V24) ? 2 : 0)]; // Read the complete frame into the byte array. data.Get(b); // Check the frame name once more if (field != "") { /* * Now catch possible errors occuring in the data * interpretation. Even if a frame is not valid regarding the * spec, the rest of the tag could be read. */ try { // Create the Frame upon the byte array data. AddId3Frame(tag, field, b, version); } catch (Exception e) { //FIXME: do we have to output anything here? } } } }
private static BitmapImage GetPicture(Id3Tag tag) { var picture = tag.Pictures.FirstOrDefault(p => p.PictureType == PictureType.BandOrOrchestra || p.PictureType == PictureType.BandOrArtistLogotype || p.PictureType == PictureType.BackCover || p.PictureType == PictureType.FrontCover); if (picture != null) { var buffer = picture.PictureData; return BitmapImageFromByteArray(buffer); } return null; }