Пример #1
0
        public static void ParseAudioFileMetaData(FileStream fs, AudioFile af)
        {
            try
            {
                TagLib.File tf   = null;
                TagLib.Tag  tags = null;
                switch (af.FileType)
                {
                case Assets.AssetFileType.MP3ID3v1ORNOTAG:
                    tf   = TagLib.File.Create(new StreamFileAbstraction(af.FileName, fs, new MemoryStream()));
                    tags = tf.GetTag(TagTypes.Id3v1);
                    break;

                case Assets.AssetFileType.MP3WITHID3v2:
                    tf   = TagLib.File.Create(new StreamFileAbstraction(af.FileName, fs, new MemoryStream()));
                    tags = tf.GetTag(TagTypes.Id3v2);
                    break;

                case Assets.AssetFileType.FLAC:
                    tf   = TagLib.File.Create(new StreamFileAbstraction(af.FileName, fs, new MemoryStream()));
                    tags = tf.GetTag(TagTypes.FlacMetadata);
                    break;
                }
                if (tf != null)
                {
                    af.Album  = tags.Album;
                    af.Artist = string.Join(" ", tags.AlbumArtists.Union(tags.Performers).Distinct());
                    af.Title  = tags.Title;
                    af.Track  = tags.Track;
                    af.Year   = tags.Year;
                }
            }
            catch { }
        }
Пример #2
0
 private async Task<SongFile> ReadTagFromFile(StorageFile file)
 {
     Stream fileStream = await file.OpenStreamForReadAsync();
     TagLib.File tagFile = TagLib.File.Create(new StreamFileAbstraction(file.Name, fileStream, fileStream));
     Tag tag = null;
     if (tagFile.MimeType == "taglib/mp3")
     {
         tag = tagFile.GetTag(TagTypes.Id3v2);
     }
     if (tagFile.MimeType == "taglib/flac")
     {
         tag = tagFile.GetTag(TagTypes.FlacMetadata);
     }
     string performers = "";
     foreach (string performer in tag.Performers)
     {
         performers += performer;
     }
     tagFile.Dispose();
     fileStream.Close();
     return new SongFile
     {
         FileName = file.Name,
         Title = tag.Title,
         Album = tag.Album,
         Tag = tag,
         Artist = performers,
         Path = file.Path
     };
 }
Пример #3
0
        //Used for debugging.
        // public static void ReadBytes(string Mp3Path, Encoding FileEncoding){
        //     Console.OutputEncoding = FileEncoding; //set the console output.
        //     byte[] MyMp3 = System.IO.File.ReadAllBytes(Mp3Path);
        //     string ByteFile = Hex.Dump(MyMp3); //Store Hex the Hex data from the Mp3 file.
        //     System.IO.File.WriteAllText("./Printouts/Mp3HexPrintout.txt", ByteFile); //Create a document containing Mp3 ByteFile (debugging).
        // }

        ///Method ensures the mp3 file is encapsulated with the appropriate data.
        ///Does not alter existing meta data.
        ///Ensures the existence of an ApeTag item with the key: CloudCoinStack.
        ///Correct Apetag has a CloudCoinStack and StackName container.
        public static TagLib.Ape.Tag CheckApeTag(TagLib.File Mp3File)
        {
            TagLib.Ape.Tag ApeTag;
            bool           hasCCS       = false;
            bool           hasStackName = false;

            // Pass a true parameter to the GetTag function in order to add one if the Mp3File doesn't already have a Mp3Tag.
            // By passing a the parameter 'TagTypes.Ape' we ensure the type is of Ape.

            try{
                ApeTag       = (TagLib.Ape.Tag)Mp3File.GetTag(TagLib.TagTypes.Ape, true);
                hasCCS       = ApeTag.HasItem("CloudCoinStack");
                hasStackName = ApeTag.HasItem("StackName");
            }
            catch (Exception e)
            {
                Console.Out.WriteLine("The process failed: {0}", e.ToString());
                ApeTag = (TagLib.Ape.Tag)Mp3File.GetTag(TagLib.TagTypes.Ape, false);
            }
            if (!hasCCS)
            {
                TagLib.Ape.Item item = new TagLib.Ape.Item("CloudCoinStack", "");
                ApeTag.SetItem(item);
            }
            if (!hasStackName)
            {
                TagLib.Ape.Item itemName = new TagLib.Ape.Item("StackName", "");
                ApeTag.SetItem(itemName);
            }
            return(ApeTag);
        }
Пример #4
0
        public static Lyrics ReadLyrics(TagLib.File file)
        {
            var id3v2 = (TagLib.Id3v2.Tag)file.GetTag(TagTypes.Id3v2);

            if (id3v2 != null)
            {
                foreach (var frame in id3v2.GetFrames <SynchronisedLyricsFrame>())
                {
                    return(new Lyrics(frame.Text));
                }
            }
            var ogg = (TagLib.Ogg.XiphComment)file.GetTag(TagTypes.Xiph);

            if (ogg != null)
            {
                var lyrics = ogg.GetField(OGG_LYRICS);
                if (lyrics != null && lyrics.Length > 0)
                {
                    return(Lyrics.FromLrc(lyrics));
                }
            }
            var tag = file.Tag;

            if (!String.IsNullOrEmpty(tag.Lyrics))
            {
                return(new Lyrics(tag.Lyrics));
            }
            return(null);
        }
Пример #5
0
 public static void SetCustomField(this File tagFile, string key, string value)
 {
     if (tagFile.GetTag(TagTypes.Id3v2) is Tag id3V2Tag)
     {
         UserTextInformationFrame userTextInformationFrame = UserTextInformationFrame.Get(id3V2Tag, key, StringType.UTF8,
                                                                                          true,
                                                                                          true);
         if (string.IsNullOrEmpty(value))
         {
             id3V2Tag.RemoveFrame(userTextInformationFrame);
         }
         else
         {
             userTextInformationFrame.Text = value.Split(';');
         }
     }
     else if (tagFile.GetTag(TagTypes.Xiph) is XiphComment xiphComment)
     {
         xiphComment.SetField(key.ToUpperInvariant(), value);
     }
     else
     {
         throw new ArgumentException(nameof(tagFile));
     }
 }
Пример #6
0
 /// <summary>
 /// Retrieve a tag with an arbitrary name.
 /// Returns an empty tag if the value isn't found or if no Xiph tags are present.
 /// </summary>
 /// <param name="TagName">
 /// A <see cref="System.String"/> containing the name of the tag to find
 /// </param>
 /// <returns>
 /// An <see cref="OggTag"/> containing the returned tag
 /// </returns>
 public OggTag GetTag(string TagName)
 {
     if (TagName.Length <= 0)
     {
         return(OggUtilities.GetEmptyTag());
     }                                                                         // Save some processing time and just exit if we haven't been given a tag name
     // Based on tasty examples @ "Accessing Hidden Gems": http://developer.novell.com/wiki/index.php/TagLib_Sharp:_Examples
     TagLib.Ogg.XiphComment XC = (TagLib.Ogg.XiphComment)m_TagLibFile.GetTag(TagTypes.Xiph);
     if (XC != null)
     {
         string[] TagValue = XC.GetField(TagName);
         if (TagValue.Length == 0)
         {
             // Tag doesn't exist, return empty
             return(OggUtilities.GetEmptyTag());
         }
         else
         {
             OggTag tmpTag;
             tmpTag.Name    = TagName;
             tmpTag.IsArray = (TagValue.Length > 1);
             tmpTag.IsEmpty = false;
             tmpTag.Values  = TagValue;
             tmpTag.Value   = TagValue[0];
             return(tmpTag);
         }
     }
     else
     {
         // No valid Xiph tags found
         return(OggUtilities.GetEmptyTag());
     }
 }
        private static Tag GetTags(TagLib.File target)
        {
            if (target.MimeType.Contains("mp3") || target.MimeType.Contains("wav"))
            {
                return(target.GetTag(TagTypes.Id3v2));
            }
            else if (target.MimeType.Contains("flac"))
            {
                return(target.GetTag(TagTypes.FlacMetadata));
            }

            return(target.GetTag(TagTypes.None));
        }
Пример #8
0
    public IEnumerator Request(string path)
    {
        //get artist and track title
        TagLib.File trk    = TagLib.File.Create(path);
        TagLib.Tag  tag    = trk.GetTag(TagLib.TagTypes.Id3v2);
        string      track  = tag.Title;
        string      artist = tag.FirstPerformer;

        if (track != null && artist != null)
        {
            WWW www = new WWW("http://api.soundcloud.com/tracks?client_id=1960bf2acbdd4e5d8d43b38df11da507&q=" + track + "," + artist);
            yield return(www);

            string str = www.text;

            if (str != null)
            {
                //take the first match and find genre
                string str1 = "\"id\"";
                Regex  r    = new Regex(str1 + @":(\d*)");
                string id   = r.Match(str).Groups [1].Value;
                www = new WWW("http://api.soundcloud.com/tracks/" + id + ".json?client_id=1960bf2acbdd4e5d8d43b38df11da507");
                yield return(www);

                str  = www.text;
                str1 = "\"genre\"";
                string str2 = "\"([^\"]*)\"";
                r     = new Regex(str1 + ":" + str2);
                genre = genreFromString(r.Match(str).Groups [1].Value);
            }
        }
        yield return(null);
    }
Пример #9
0
        public void CheckMakerNote(File file)
        {
            var tag = file.GetTag(TagTypes.TiffIFD) as IFDTag;

            Assert.IsNotNull(tag, "tag");

            var makernote_ifd =
                tag.ExifIFD.GetEntry(0, (ushort)ExifEntryTag.MakerNote) as MakernoteIFDEntry;

            Assert.IsNotNull(makernote_ifd, "makernote ifd");
            Assert.AreEqual(MakernoteType.Nikon3, makernote_ifd.MakernoteType);

            var structure = makernote_ifd.Structure;

            Assert.IsNotNull(structure, "structure");
            {
                var entry = structure.GetEntry(0, 0x01) as UndefinedIFDEntry;
                Assert.IsNotNull(entry);
                var read_bytes     = entry.Data;
                var expected_bytes = new ByteVector(new byte[] { 48, 50, 49, 48 });

                Assert.AreEqual(expected_bytes.Count, read_bytes.Count);
                for (int i = 0; i < expected_bytes.Count; i++)
                {
                    Assert.AreEqual(expected_bytes[i], read_bytes[i]);
                }
            }
            {
                var entry = structure.GetEntry(0, 0x05) as StringIFDEntry;
                Assert.IsNotNull(entry, "entry 0x05");
                Assert.AreEqual("AUTO        ", entry.Value);
            }
            {
                var entry = structure.GetEntry(0, 0x09) as StringIFDEntry;
                Assert.IsNotNull(entry, "entry 0x09");
                Assert.AreEqual("                   ", entry.Value);
            }
            {
                var entry = structure.GetEntry(0, 0x0B) as SShortArrayIFDEntry;
                Assert.IsNotNull(entry, "entry 0x0B");
                var values = entry.Values;

                Assert.IsNotNull(values, "values of entry 0x0B");
                Assert.AreEqual(2, values.Length);
                Assert.AreEqual(0, values[0]);
                Assert.AreEqual(0, values[1]);
            }
            {
                var entry = structure.GetEntry(0, 0x84) as RationalArrayIFDEntry;
                Assert.IsNotNull(entry, "entry 0x84");
                var values = entry.Values;

                Assert.IsNotNull(values, "values of entry 0x84");
                Assert.AreEqual(4, values.Length);
                Assert.AreEqual(180.0d / 10.0d, (double)values[0]);
                Assert.AreEqual(2000.0d / 10.0d, (double)values[1]);
                Assert.AreEqual(35.0d / 10.0d, (double)values[2]);
                Assert.AreEqual(56.0d / 10.0d, (double)values[3]);
            }
        }
Пример #10
0
        public void TestPrivateFrame()
        {
            MockFileSystem fileSystem = new MockFileSystem();

            fileSystem.AddFile(@"C:\test.mp3", new MockFileData(System.IO.File.ReadAllBytes(@"TestData\test.mp3")));

            File.IFileAbstraction mp3File = fileSystem.File.CreateFileAbstraction(@"C:\test.mp3");
            File file = File.Create(mp3File);

            Tag id3V2Tag = (Tag)file.GetTag(TagTypes.Id3v2, true);

            // Get the private frame, create if necessary.
            PrivateFrame frame = PrivateFrame.Get(id3V2Tag, "SW/Uid", true);

            string uid = Guid.NewGuid().ToString("N");

            frame.PrivateData = Encoding.Unicode.GetBytes(uid);

            file.Save();


            File actualFile = File.Create(mp3File);

            id3V2Tag = (Tag)actualFile.GetTag(TagTypes.Id3v2, true);
            // Get the private frame, create if necessary.
            PrivateFrame actualFrame = PrivateFrame.Get(id3V2Tag, "SW/Uid", true);

            // Set the frame data to your value.  I am 90% sure that these are encoded with UTF-16.
            string actualUid = Encoding.Unicode.GetString(actualFrame.PrivateData.Data);

            actualUid.Should().Be(uid);
        }
 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);
 }
Пример #12
0
        private void TestTagLibLoading()
        {
            TagLib.File file = null;

            if (!System.IO.File.Exists(path))
            {
                tool.show(3, "Invalid path", path);
                return;
            }
            try
            {
                //if(isMP3())
                file = TagLib.File.Create(path);
            }
            catch (TagLib.CorruptFileException e)
            {
                tool.show(2, e.Message);
                return;
            }
            if (file == null)
            {
                return;
            }
            file.Mode = TagLib.File.AccessMode.Read;
            file.GetTag(TagTypes.AllTags);
        }
Пример #13
0
        /// <summary>
        ///   Based on the Options set, use the correct version for ID3
        ///   Eventually remove V1 or V2 tags, if set in the options
        /// </summary>
        /// <param name = "File"></param>
        public static File FormatID3Tag(File file)
        {
            if (file.MimeType == "taglib/mp3")
            {
                var options   = (ServiceLocator.Current.GetInstance(typeof(ISettingsManager)) as ISettingsManager)?.GetOptions;
                Tag id3v2_tag = file.GetTag(TagTypes.Id3v2) as Tag;
                if (id3v2_tag != null && options.MainSettings.ID3V2Version > 0)
                {
                    id3v2_tag.Version = (byte)options.MainSettings.ID3V2Version;
                }

                // Remove V1 Tags, if checked or "Save V2 only checked"
                if (options.MainSettings.RemoveID3V1 || options.MainSettings.ID3Version == 2)
                {
                    file.RemoveTags(TagTypes.Id3v1);
                }

                // Remove V2 Tags, if checked or "Save V1 only checked"
                if (options.MainSettings.RemoveID3V2 || options.MainSettings.ID3Version == 1)
                {
                    file.RemoveTags(TagTypes.Id3v2);
                }

                // Remove V2 Tags, if Ape checked
                if (options.MainSettings.ID3V2Version == 0)
                {
                    file.RemoveTags(TagTypes.Id3v2);
                }
                else
                {
                    file.RemoveTags(TagTypes.Ape);
                }
            }
            return(file);
        }
Пример #14
0
        public static void DumpXiphMetadata(File tagFile)
        {
            TagLib.Ogg.XiphComment tags = (TagLib.Ogg.XiphComment)tagFile.GetTag(TagTypes.Xiph);

            foreach (string fieldName in tags.Distinct().OrderBy(t => t))
            {
                string[] fieldValue = tags.GetField(fieldName);
                if (fieldValue.Length > 1)
                {
                    Console.WriteLine("{0} ({1}):", fieldName, fieldValue.Length);
                    foreach (string fv in fieldValue)
                    {
                        WriteLineWithIndent(4, fv);
                    }
                }
                else if (fieldValue.Length == 1)
                {
                    Console.WriteLine("{0}:", fieldName);
                    WriteLineWithIndent(4, fieldValue[0]);
                }
                else
                {
                    Console.WriteLine("{0} (No Value)", fieldName);
                }
            }
        }
Пример #15
0
        public void CheckMakerNote(File file)
        {
            var tag = file.GetTag(TagTypes.TiffIFD) as IFDTag;

            Assert.IsNotNull(tag, "tag");

            var makernote_ifd =
                tag.ExifIFD.GetEntry(0, (ushort)ExifEntryTag.MakerNote) as MakernoteIFDEntry;

            Assert.IsNotNull(makernote_ifd, "makernote ifd");
            Assert.AreEqual(MakernoteType.Sony, makernote_ifd.MakernoteType);

            var structure = makernote_ifd.Structure;

            Assert.IsNotNull(structure, "structure");
            //Tag info from http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Sony.html
            //0x0102: image quality
            {
                var entry = structure.GetEntry(0, 0x0102) as LongIFDEntry;
                Assert.IsNotNull(entry, "entry 0x0102");
                Assert.AreEqual(2, entry.Value);
            }
            //0x0115: white balance
            {
                var entry = structure.GetEntry(0, 0x0115) as LongIFDEntry;
                Assert.IsNotNull(entry, "entry 0x0115");
                Assert.AreEqual(0, entry.Value);
            }
            //0xb026: image stabilizer
            {
                var entry = structure.GetEntry(0, 0xb026) as LongIFDEntry;
                Assert.IsNotNull(entry, "entry 0xb026");
                Assert.AreEqual(0, entry.Value);
            }
        }
Пример #16
0
        public void PopulateList()
        {
            DirectoryInfo dirInfo = new DirectoryInfo(MusicFile.loc);

            FileSystemInfo[] files = null;
            try {
                files = dirInfo.GetFileSystemInfos("*.mp3");
            }
            catch (Exception e)
            {
            }

            TagLib.File file = null;
            foreach (var f in files)
            {
                try { file = TagLib.File.Create(f.FullName); }
                catch (Exception e)
                {
                    continue;
                }

                Tag tags = file.GetTag(TagTypes.Id3v2);
                if (tags != null)
                {
                    mf = new MusicFile(f.FullName, tags.Title, tags.Album, tags.FirstPerformer);
                }

                MusicFilesCB.Add(mf);
            }
        }
        public void CheckJpegComment(File file, int i)
        {
            var tag = file.GetTag(TagTypes.JpegComment) as JpegCommentTag;

            Assert.IsNotNull(tag, $"JpegTag Tag not contained: index {i}");

            Assert.AreEqual("Created with GIMP", tag.Comment, $"index {i}");
        }
        public void CheckXmp(File file, int i)
        {
            var tag = file.GetTag(TagTypes.XMP) as XmpTag;

            Assert.IsNotNull(tag, $"XMP Tag not contained: index {i}");

            Assert.AreEqual("test description", tag.Comment);
        }
Пример #19
0
        private async Task ReadTags(TagLib.File tagFile)
        {
            Tag tags = tagFile.GetTag(TagTypes.Id3v2);

            Title  = tags.Title;
            Artsit = tags.Performers.FirstOrDefault();
            Album  = tags.Album;
            Cover  = await tags.Pictures[0].ToBitmapImage(new Size(120, 120));
        }
Пример #20
0
        public static string GetCustomField(this File tagFile, string key)
        {
            if (tagFile.GetTag(TagTypes.Id3v2) is Tag id3V2Tag)
            {
                UserTextInformationFrame userTextInformationFrame = UserTextInformationFrame.Get(id3V2Tag, key, StringType.UTF8,
                                                                                                 false,
                                                                                                 true);

                return(userTextInformationFrame != null?string.Join(';', userTextInformationFrame.Text) : null);
            }

            if (tagFile.GetTag(TagTypes.Xiph) is XiphComment xiphComment)
            {
                return(xiphComment.GetFirstField(key.ToUpperInvariant()));
            }

            throw new ArgumentException(nameof(tagFile));
        }
Пример #21
0
        public void CheckXMP(File file)
        {
            var tag = file.GetTag(TagTypes.XMP) as XmpTag;

            Assert.IsNotNull(tag, "tag");

            Assert.AreEqual(new string[] { }, tag.Keywords);
            Assert.AreEqual("OLYMPUS CORPORATION", tag.Make);
            Assert.AreEqual("C5060WZ", tag.Model);
            Assert.AreEqual("Adobe Photoshop Elements 4.0", tag.Software);
        }
        public void CheckExif(File file, int i)
        {
            var tag = file.GetTag(TagTypes.TiffIFD) as IFDTag;

            Assert.IsNotNull(tag, $"Tiff Tag not contained: index {i}");

            var exif_ifd = tag.Structure.GetEntry(0, IFDEntryTag.ExifIFD) as SubIFDEntry;

            Assert.IsNotNull(exif_ifd, $"Exif SubIFD not contained: index {i}");

            Assert.AreEqual("test comment", tag.Comment, $"index {i}");
        }
Пример #23
0
        public void CheckMakerNote(File file)
        {
            var tag = file.GetTag(TagTypes.TiffIFD) as IFDTag;

            Assert.IsNotNull(tag, "tag");

            var makernote_ifd =
                tag.ExifIFD.GetEntry(0, (ushort)ExifEntryTag.MakerNote) as MakernoteIFDEntry;

            Assert.IsNotNull(makernote_ifd, "makernote ifd");
            Assert.AreEqual(MakernoteType.Olympus2, makernote_ifd.MakernoteType);

            var structure = makernote_ifd.Structure;

            Assert.IsNotNull(structure, "structure");

            /*{
             *      var entry = structure.GetEntry (0, 0x01) as UndefinedIFDEntry;
             *      Assert.IsNotNull (entry);
             *      ByteVector read_bytes = entry.Data;
             *      ByteVector expected_bytes = new ByteVector (new byte [] {48, 50, 49, 48});
             *
             *      Assert.AreEqual (expected_bytes.Count, read_bytes.Count);
             *      for (int i = 0; i < expected_bytes.Count; i++)
             *              Assert.AreEqual (expected_bytes[i], read_bytes[i]);
             * }
             * {
             *      var entry = structure.GetEntry (0, 0x04) as StringIFDEntry;
             *      Assert.IsNotNull (entry, "entry 0x04");
             *      Assert.AreEqual ("FINE   ", entry.Value);
             * }
             * {
             *      var entry = structure.GetEntry (0, 0x08) as StringIFDEntry;
             *      Assert.IsNotNull (entry, "entry 0x08");
             *      Assert.AreEqual ("NORMAL      ", entry.Value);
             * }
             * {
             *      var entry = structure.GetEntry (0, 0x92) as SShortIFDEntry;
             *      Assert.IsNotNull (entry, "entry 0x92");
             *      Assert.AreEqual (0, entry.Value);
             * }
             * {
             *      var entry = structure.GetEntry (0, 0x9A) as RationalArrayIFDEntry;
             *      Assert.IsNotNull (entry, "entry 0x9A");
             *      var values = entry.Values;
             *
             *      Assert.IsNotNull (values, "values of entry 0x9A");
             *      Assert.AreEqual (2, values.Length);
             *      Assert.AreEqual (78.0d/10.0d, (double) values[0]);
             *      Assert.AreEqual (78.0d/10.0d, (double) values[1]);
             * }*/
        }
Пример #24
0
        /// <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);
        }
Пример #25
0
        public static void WriteLyrics(TagLib.File file, Lyrics lyrics)
        {
            var tag   = file.Tag;
            var id3v2 = (TagLib.Id3v2.Tag)file.GetTag(TagTypes.Id3v2);
            var ogg   = (TagLib.Ogg.XiphComment)file.GetTag(TagTypes.Xiph);

            tag.Lyrics = lyrics.ToSimple();
            if (id3v2 != null)
            {
                foreach (var frame in id3v2.GetFrames <SynchronisedLyricsFrame>().ToList())
                {
                    id3v2.RemoveFrame(frame);
                }
                var new_frame = new SynchronisedLyricsFrame("lyrics", null, SynchedTextType.Lyrics, StringType.Latin1);
                new_frame.Text = lyrics.ToSynchedText();
                id3v2.AddFrame(new_frame);
            }
            if (ogg != null)
            {
                ogg.SetField(OGG_LYRICS, lyrics.ToLrc());
            }
        }
Пример #26
0
 private static void CopyTags(File originalTags, File newTags)
 {
     if ((originalTags.TagTypes & TagTypes.Png) == TagTypes.Png)
     {
         if (originalTags.GetTag(TagTypes.Png) is PngTag tag &&
             newTags.GetTag(TagTypes.Png, true) is PngTag newTag)
         {
             foreach (KeyValuePair <string, string> kvp in tag)
             {
                 newTag.SetKeyword(kvp.Key, kvp.Value);
             }
         }
     }
     if ((originalTags.TagTypes & TagTypes.XMP) == TagTypes.XMP)
     {
         if (originalTags.GetTag(TagTypes.XMP) is XmpTag tag &&
             newTags.GetTag(TagTypes.XMP, true) is XmpTag newTag)
         {
             Console.WriteLine("DEBUG: new XMP Tag values");
             foreach (var node in newTag.NodeTree.Children)
             {
                 MetaExtract.WriteTaglibXmpNodeTree(node, "");
             }
             // Don't bother copying camera/scanner related information.
             // We just want the creator/copyright/description type information.
             foreach (var node in tag.NodeTree.Children)
             {
                 if (node.Namespace == "http://purl.org/dc/elements/1.1/" ||
                     node.Namespace == "http://creativecommons.org/ns#" ||
                     node.Namespace == "http://www.metadataworkinggroup.com/schemas/collections/" ||
                     (node.Namespace == "http://ns.adobe.com/exif/1.0/" && node.Name == "UserComment"))
                 {
                     newTag.NodeTree.AddChild(node);
                 }
             }
         }
     }
 }
Пример #27
0
        private static async Task <int> importFiles(StorageFolder folder, int totalCount, int currentCount, JsonObject library, IProgress <InitializeLibraryTaskProgress> progress)
        {
            IReadOnlyList <StorageFolder> folders = await folder.GetFoldersAsync();

            IReadOnlyList <StorageFile> files = await folder.GetFilesAsync();

            // create the library json data
            if (library == null)
            {
                library = JsonObject.Parse("{ \"artists\": [] }");
            }

            foreach (StorageFile file in files)
            {
                if (file.ContentType == "audio/mpeg")
                {
                    using (Stream fileStream = await file.OpenStreamForReadAsync())
                    {
                        // get the id3 info
                        TagLib.File tagFile = TagLib.File.Create(new StreamFileAbstraction(file.Name, fileStream, fileStream));
                        TagLib.Tag  tag     = tagFile.GetTag(TagTypes.Id3v2);

                        // get the album from the library file
                        JsonObject album = GetAlbum(library, tag);
                        JsonObject track = new JsonObject();
                        track.Add("title", JsonValue.CreateStringValue(tag.Title));
                        track.Add("number", JsonValue.CreateNumberValue(tag.Track));

                        currentCount++;

                        // add tracks to the library
                        album.GetNamedArray("tracks").Add(track);

                        // notify user of progress
                        progress.Report(new InitializeLibraryTaskProgress {
                            Progress = (int)Math.Round((float)currentCount / (float)totalCount * 100),
                            Message  = "Importing " + tag.Album + " - " + tag.Title + " (" + currentCount + " / " + totalCount + ")"
                        });
                    }
                }
            }

            foreach (StorageFolder childFolder in folders)
            {
                currentCount = await importFiles(childFolder, totalCount, currentCount, library, progress);
            }

            return(currentCount);
        }
Пример #28
0
        private static void SetTagData(TagLib.File file, SongTagData tagData)
        {
            file.RemoveTags(TagTypes.Id3v1);
            file.RemoveTags(TagTypes.Id3v2);
            file.RemoveTags(TagTypes.Ape);

            // We set only Id3v2 tag.
            // Id3v1 stores genres as index from predefined genre list.
            // This list is pretty limited and doesn't contain frequently used tags like 'Symphonic Metal' or 'Nu metal'.
            // The list of available genres for Id3v2 tag could be obtained from TagLib.Genres.Audio.
            var tag = file.GetTag(TagTypes.Id3v2, true);

            FillTag(tag, tagData);
            file.Save();
        }
Пример #29
0
        public bool ReadID3Info()
        {
            if (loaded)
            {
                return(true);
            }
            if (tool.IsAudioFile(path))
            {
                title = Path.GetFileNameWithoutExtension(path);
                try
                {
                    file = TagLib.File.Create(path);
                    file.GetTag(TagTypes.AllTags);
                    album    = file.Tag.Album;
                    artist   = file.Tag.FirstAlbumArtist;
                    track    = file.Tag.Track;
                    lyrics   = file.Tag.Lyrics;
                    pictures = file.Tag.Pictures;
                    year     = file.Tag.Year.ToString();
                    length   = file.Length.ToString();
                    if (!string.IsNullOrEmpty(file.Tag.FirstGenre))
                    {
                        genres = file.Tag.FirstGenre; //genre loading appers tp be broken
                    }
                    if (!string.IsNullOrEmpty(file.Tag.Title))
                    {
                        title = file.Tag.Title;
                    }

                    return(loaded = true);
                }
                catch (Exception e)
                {
                    TagLoadingLog.Add(string.Concat("--> Failed to Get All Tags: \n", e.Message, "\n", path));
                    invalid = true;
                    return(loaded = false);
                }
                finally
                {
                    if (file != null)
                    {
                        file.Dispose();
                    }
                }
            }
            invalid = true;
            return(false);
        }
Пример #30
0
 /// <summary>Function to read the various tags from file, if available
 /// These will be checked in various get functions
 /// </summary>
 private void ReadTags()
 {
     //currentFile = TagLib.File.Create(FileInfoView.FocusedItem.SubItems[4].Text);
     id3v1 = currentFile.GetTag(TagLib.TagTypes.Id3v1) as TagLib.Id3v1.Tag;
     id3v2 = currentFile.GetTag(TagLib.TagTypes.Id3v2) as TagLib.Id3v2.Tag;
     apple = currentFile.GetTag(TagLib.TagTypes.Apple) as TagLib.Mpeg4.AppleTag;
     ape   = currentFile.GetTag(TagLib.TagTypes.Ape) as TagLib.Ape.Tag;
     //            asf = currentFile.GetTag(TagLib.TagTypes.Asf) as TagLib.Asf.Tag;
     ogg  = currentFile.GetTag(TagLib.TagTypes.Xiph) as TagLib.Ogg.XiphComment;
     flac = currentFile.GetTag(TagLib.TagTypes.FlacMetadata) as TagLib.Flac.Metadata;
 }
Пример #31
0
        private void InitializeTag()
        {
            if (Location == null || !Location.IsFile || MediaType != "audio/mpeg")
            {
                throw new InvalidOperationException("Only local MP3 files can be tagged - tracks with an invalid or remote location cannot be tagged");
            }

            if (file == null)
            {
                file = TagLib.File.Create(Location.LocalPath);
            }

            if (tag == null)
            {
                tag = file.GetTag(TagTypes.Id3v2) as TagLib.Id3v2.Tag;
            }
        }
Пример #32
0
        void PopulateFromId3v2(File file, Tag tag)
        {
            if (!file.TagTypes.HasFlag(TagTypes.Id3v2))
                return;

            var id3v2 = (TagLib.Id3v2.Tag)file.GetTag(TagTypes.Id3v2);

            tag.ImageData = GetImageData(id3v2);

            // ID3v2 Tags Reference: http://id3.org/id3v2.4.0-frames
            tag.InitialKey = GetTextFrame(id3v2, "TKEY") ?? GetUserTextFrame(id3v2, "Initial key");
            tag.Artist = JoinPerformers(id3v2.Performers);
            tag.Title = id3v2.Title;
            tag.Year = ToStringOrDefault(id3v2.Year);
            tag.Genre = id3v2.JoinedGenres;
            tag.Publisher = GetTextFrame(id3v2, "TPUB") ?? GetUserTextFrame(id3v2, "Publisher");
            tag.Bpm = ToStringOrDefault(id3v2.BeatsPerMinute) ?? GetUserTextFrame(id3v2, "BPM (beats per minute)");
        }
Пример #33
0
        public void ReadTags(string filePath)
        {
            ChannelProps.Clear();
            fileTag = TagLib.File.Create(filePath);

            ChannelProps.Add(((double)fileTag.Properties.AudioSampleRate/1000).ToString());
            ChannelProps.Add(fileTag.Properties.AudioBitrate.ToString());
            ChannelProps.Add(fileTag.Properties.AudioChannels.ToString());
            ChannelProps.Add(String.Format("{0:D2}:{1:D2}:{2:D2}", (int)fileTag.Properties.Duration.TotalHours,
                fileTag.Properties.Duration.Minutes, fileTag.Properties.Duration.Seconds));

            TagLib.Id3v1.Tag id3v1 = fileTag.GetTag(TagLib.TagTypes.Id3v1) as TagLib.Id3v1.Tag;
            TagLib.Id3v2.Tag id3v2 = fileTag.GetTag(TagLib.TagTypes.Id3v2) as TagLib.Id3v2.Tag;
            TagLib.Mpeg4.AppleTag apple = fileTag.GetTag(TagLib.TagTypes.Apple) as TagLib.Mpeg4.AppleTag;
            TagLib.Ape.Tag ape = fileTag.GetTag(TagLib.TagTypes.Ape) as TagLib.Ape.Tag;
            TagLib.Asf.Tag asf = fileTag.GetTag(TagLib.TagTypes.Asf) as TagLib.Asf.Tag;
            TagLib.Ogg.XiphComment ogg = fileTag.GetTag(TagLib.TagTypes.Xiph) as TagLib.Ogg.XiphComment;
        }
Пример #34
0
        void PopulateFromId3v1(File file, Tag tag)
        {
            if (!file.TagTypes.HasFlag(TagTypes.Id3v1))
                return;

            var id3v1 = (TagLib.Id3v1.Tag) file.GetTag(TagTypes.Id3v1);

            tag.Artist = tag.Artist ?? JoinPerformers(id3v1.Performers);
            tag.Title = tag.Title ?? id3v1.Title;
            tag.Year = tag.Year ?? ToStringOrDefault(id3v1.Year);
            tag.Genre = tag.Genre ?? id3v1.JoinedGenres;
            //tag.Publisher = tag.Publisher ?? id3v1.
            tag.Bpm = tag.Bpm ?? ToStringOrDefault(id3v1.BeatsPerMinute);
        }
 public ZuneWMATagContainer(File file)
     : base(file)
 {
     _file = file;
     _tag = (Tag)file.GetTag(TagTypes.Asf);
 }
        /// <summary>
        /// Saves the new/changed values to the file
        /// </summary>
        /// <param name="id3">New values to be saved</param>
        /// <param name="oldId3">Old values (needed for log file)</param>
        /// <returns>Success or not</returns>
        public static bool Save(File id3, File oldId3)
        {
            try
            {
                Logger.Info("---------------");
                Logger.Info($"Changing values for \"{id3.Name}\"");
                var newTags = id3.TagTypes != TagTypes.Id3v2 ? id3.Tag : id3.GetTag(TagTypes.Id3v2);
                var oldTags = oldId3.TagTypes != TagTypes.Id3v2 ? oldId3.Tag : oldId3.GetTag(TagTypes.Id3v2);
                foreach (var property in Properties)
                {
                    if (property.Equals("Performers") || property.Equals("Genres"))
                        LogDifferences(newTags.GetPropertyValue($"Joined{property}"),
                            oldTags.GetPropertyValue($"Joined{property}"), property, newTags.GetPropertyValue(property),
                            oldTags.GetPropertyValue(property));
                    else
                        LogDifferences(newTags.GetPropertyValue(property),
                            oldTags.GetPropertyValue(property), property);
                }
                if (id3.TagTypes == TagTypes.Id3v2)
                    LogDifferences(newTags.GetPopularimeterFrame().Rating.ToStars(), oldTags.GetPopularimeterFrame().Rating.ToStars(), "Rating");

                id3.Save();
                Logger.Info("---------------");
                return true;
            }
            catch (CorruptFileException ex)
            {
                Logger.Error($"An exception occured while changing values for \"{id3.Name}\"", ex);
                return false;
            }
        }
Пример #37
0
        /// <summary>
        ///   Based on the Options set, use the correct version for ID3
        ///   Eventually remove V1 or V2 tags, if set in the options
        /// </summary>
        /// <param name = "File"></param>
        public static File FormatID3Tag(File file)
        {
            if (file.MimeType == "taglib/mp3")
              {
            Tag id3v2_tag = file.GetTag(TagTypes.Id3v2) as Tag;
            if (id3v2_tag != null && Options.MainSettings.ID3V2Version > 0)
              id3v2_tag.Version = (byte)Options.MainSettings.ID3V2Version;

            // Remove V1 Tags, if checked or "Save V2 only checked"
            if (Options.MainSettings.RemoveID3V1 || Options.MainSettings.ID3Version == 2)
              file.RemoveTags(TagTypes.Id3v1);

            // Remove V2 Tags, if checked or "Save V1 only checked"
            if (Options.MainSettings.RemoveID3V2 || Options.MainSettings.ID3Version == 1)
              file.RemoveTags(TagTypes.Id3v2);

            // Remove V2 Tags, if Ape checked
            if (Options.MainSettings.ID3V2Version == 0)
            {
              file.RemoveTags(TagTypes.Id3v2);
            }
            else
            {
              file.RemoveTags(TagTypes.Ape);
            }
              }
              return file;
        }