This abstract class provides generic access to standard tag features. All tag types will extend this class.
Because not every tag type supports the same features, it may be useful to check that the value is stored by re-reading the property after it is stored.
Esempio n. 1
1
 public static void Duplicate(Tag source, Tag target, bool overwrite)
 {
     if (source == null)
     {
         throw new ArgumentNullException("source");
     }
     if (target == null)
     {
         throw new ArgumentNullException("target");
     }
     source.CopyTo(target, overwrite);
 }
Esempio n. 2
0
    public static string GetFileDescription(string path)
    {
        TagLib.Tag tags = TagLib.File.Create(path).Tag;

        StringBuilder sb      = new StringBuilder();
        string        artists = string.Join("", tags.AlbumArtists);

        if (MoreThanOneSymbol(artists))
        {
            sb.Append(artists);
        }

        string performers = string.Join("", tags.Performers);

        if (MoreThanOneSymbol(performers) && !performers.Equals(artists))
        {
            sb.Append(sb.Length > 0 ? SPACING : string.Empty);
            sb.Append(performers);
        }

        if (MoreThanOneSymbol(tags.Title))
        {
            sb.Append(sb.Length > 0 ? SPACING : string.Empty);
            sb.Append(tags.Title);
        }

        if (MoreThanOneSymbol(tags.Year.ToString()))
        {
            sb.Append(sb.Length > 0 ? SPACING : string.Empty);
            sb.Append(tags.Year);
        }

        return(sb.Length > 0 ? sb.ToString() : string.Empty);
    }
Esempio n. 3
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);
    }
Esempio n. 4
0
        public TrackFile(string path, string root = null)
        {
            var track = TagLib.File.Create(path);

            if (String.IsNullOrEmpty(root) || (!System.IO.Path.IsPathRooted(path)) || !path.StartsWith(root))
            {
                Path = path;
            }
            else
            {
                Path = path.Remove(0, root.Length + 1);
            }
            Tag = track.Tag;

            Genres = TrimStrings(Tag.Genres);

            if (track.GetTag(TagTypes.Id3v2) is TagLib.Id3v2.Tag id3v2)
            {
                Comments = id3v2.GetAllComments(TagLib.Id3v2.Tag.Language);
                Ratings  = id3v2.GetAllRatings();
            }
            else
            {
                Comments = new Dictionary <string, string>();
                Ratings  = new List <TrackRating>();
            }

            MediaMonkey = new MediaMonkeyTags(this);
            Dances      = new TrackDances(this);
        }
Esempio n. 5
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 { }
        }
Esempio n. 6
0
 public static void CheckTags(Tag tag)
 {
     Assert.AreEqual (-10.28, tag.ReplayGainTrackGain);
                 Assert.AreEqual(0.999969, tag.ReplayGainTrackPeak);
                 Assert.AreEqual(-9.98, tag.ReplayGainAlbumGain);
                 Assert.AreEqual(0.999980, tag.ReplayGainAlbumPeak);
 }
Esempio n. 7
0
        public async Task MapTags(Tag tags)
        {
            var trackNumber = GetTrackNumber();

            if (trackNumber.HasValue)
            {
                tags.Track = (uint)trackNumber.Value;
            }

            tags.Title    = IsMovingExtraTitleToSubtitle ? Track.Title : Track.ToTitleString();
            tags.Subtitle = IsMovingExtraTitleToSubtitle ? Track.TitleExtended : null;

            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();
        }
Esempio n. 8
0
 public static void SetTags(Tag tag)
 {
     tag.ReplayGainTrackGain = -10.28;
                 tag.ReplayGainTrackPeak = 0.999969;
                 tag.ReplayGainAlbumGain = -9.98;
                 tag.ReplayGainAlbumPeak = 0.999980;
 }
Esempio n. 9
0
 public static void GetAndSavePictureByTag(Tag tag, string songCoverPath, string songId)
 {
     var ms = new MemoryStream(tag.Pictures[0].Data.Data);
     var image = Image.FromStream(ms);
     var pathSongAlbumCover = songCoverPath + songId + ".jpg";
     image.Save(pathSongAlbumCover);
 }
Esempio n. 10
0
 public FileEntryClass(string file)
 {
     TagLib.File audiofile = TagLib.File.Create(file);
     Tag      = audiofile.Tag;
     filename = Path.GetFileName(file);
     filepath = file;
     duration = audiofile.Properties.Duration;
 }
 private static BitmapSource getPic(TL.Tag tag)
 {
     if (tag.Pictures == null || tag.Pictures.Length == 0)
     {
         return(null);
     }
     return(Graphic.Byte2BitmapSource(tag.Pictures[0].Data.Data));
 }
Esempio n. 12
0
        public MP3File(string path)
        {
            _path = path; // for save case
            if (!MP3Api.isValidFile(path))
                return;

            _tags = TagLib.File.Create(path).Tag;
        }
Esempio n. 13
0
 public XmlArtwork(Tag tag)
 {
     if (tag.Pictures.Length > 0)
     {
         Image img = Image.FromStream(new MemoryStream(tag.Pictures[0].Data.Data));
         this.Width = img.Width;
         this.Height = img.Height;
     }
 }
Esempio n. 14
0
        public static AlbumTrackInfo GetPictureByWebService(Tag tag, string titleVk, string artistVk, string fileName)
        {
            string artist = string.Empty;
            string album = string.Empty;
            string track = string.Empty;
            var info = new AlbumTrackInfo();

            if (tag != null)
            {
                if (string.IsNullOrEmpty(tag.Album) == false)
                {
                    album = tag.Album.ToUtf8();
                }

                if (string.IsNullOrEmpty(tag.Title) == false)
                {
                    track = tag.Title.ToUtf8();
                }

                if (string.IsNullOrEmpty(tag.Artists.FirstOrDefault()) == false)
                {
                    var artistWithoutEncoding = tag.Artists.FirstOrDefault();
                    if (artistWithoutEncoding != null)
                    {
                        artist = artistWithoutEncoding.ToUtf8();
                    }

                }

                var albumTrackInfoByTag = CheckContent(artist, album, track);
                if (albumTrackInfoByTag != null)
                {
                    return albumTrackInfoByTag;
                }
            }

               var  albumTrackInfo = CheckContent(artistVk.ToUtf8(), "", titleVk.ToUtf8());

            if (albumTrackInfo != null)
            {
                return albumTrackInfo;
            }

            albumTrackInfo = CheckContent("", "", fileName);

            if (albumTrackInfo != null)
            {
                return albumTrackInfo;
            }

            info.PicturePath = FilePathContainer.SongAlbumCoverPathPhysical + "default_song_album.jpg";
            return info;
            //songAlbumPicturePath = TagsInformationGetter.SongAlbumPicturePath(audioFile, lastFm, songAlbumPicturePath, ref albumInfoContent);

            //ImageSaver.SongAlbumCoverPath + "default_song_album.jpg";
        }
Esempio n. 15
0
        public AudioFile(string nameOnServer, string serverPath, TagLib.Tag tag, TagLib.Properties properties)
        {
            this.NameOnServer = nameOnServer;
            this.Title        = tag.Title;

            //this.Path = string.Format("/AudioFiles/{0}", tag.Title);
            this.ServerPath = serverPath;
            this.Duration   = properties.Duration;
            this.DateAdded  = DateTime.Now;
        }
Esempio n. 16
0
 private void Read(ReadStyle propertiesStyle)
 {
     this.tag = new CombinedTag();
     base.Mode = TagLib.File.AccessMode.Read;
     try
     {
         FileParser parser = new FileParser(this);
         if (propertiesStyle == ReadStyle.None)
         {
             parser.ParseTag();
         }
         else
         {
             parser.ParseTagAndProperties();
         }
         base.InvariantStartPosition = parser.MdatStartPosition;
         base.InvariantEndPosition = parser.MdatEndPosition;
         this.udta_box = parser.UserDataBox;
         if (((this.udta_box != null) && (this.udta_box.GetChild(BoxType.Meta) != null)) && (this.udta_box.GetChild(BoxType.Meta).GetChild(BoxType.Ilst) != null))
         {
             base.TagTypesOnDisk |= TagTypes.Apple;
         }
         if (this.udta_box == null)
         {
             this.udta_box = new IsoUserDataBox();
         }
         this.apple_tag = new AppleTag(this.udta_box);
         TagLib.Tag[] tags = new TagLib.Tag[] { this.apple_tag };
         this.tag.SetTags(tags);
         if (propertiesStyle == ReadStyle.None)
         {
             base.Mode = TagLib.File.AccessMode.Closed;
         }
         else
         {
             IsoMovieHeaderBox movieHeaderBox = parser.MovieHeaderBox;
             if (movieHeaderBox == null)
             {
                 base.Mode = TagLib.File.AccessMode.Closed;
                 throw new CorruptFileException("mvhd box not found.");
             }
             IsoAudioSampleEntry audioSampleEntry = parser.AudioSampleEntry;
             IsoVisualSampleEntry visualSampleEntry = parser.VisualSampleEntry;
             ICodec[] codecs = new ICodec[] { audioSampleEntry, visualSampleEntry };
             this.properties = new TagLib.Properties(movieHeaderBox.Duration, codecs);
         }
     }
     finally
     {
         base.Mode = TagLib.File.AccessMode.Closed;
     }
 }
Esempio n. 17
0
        /// <summary>
        /// Funkcja wczytująca pliki z podanej lokalizacji do głównej siatki
        /// </summary>
        /// <param name="filePaths">Tablica plików do wczytania</param>
        public void appendIntoMainGrid(string[] filePaths)
        {
            toolStripProgressBar1.Minimum = 0;                      // ustawienie wartości minimalnej progress bara
            toolStripProgressBar1.Maximum = filePaths.Length;       // ustawienie wartości maksymalnej progress bara
            toolStripProgressBar1.Value   = 0;                      // ustawienie wartości początkowej

            foreach (string str in filePaths)
            {
                tablica.Add(TagLib.File.Create(str));                   // dodanie pliku do tablicy agregującej wszystkie pliki
                string[] info = new string[Mp3File.numberOfFields + 1]; // stworzenie tablicy jednowymiarowej o tylu komorkach ile jest w enumie (wszystkie ktore obslugujemy)

                TagLib.Tag nowy = tablica.Last().Tag;

                info[0] = (++lp).ToString();                            // wpisanie liczby porządkowej
                info[(int)TagFields.Artist]      = nowy.JoinedPerformers;
                info[(int)TagFields.Title]       = nowy.Title;
                info[(int)TagFields.Album]       = nowy.Album;
                info[(int)TagFields.Track]       = nowy.Track.ToString();
                info[(int)TagFields.AlbumArtist] = nowy.JoinedAlbumArtists;
                info[(int)TagFields.Discnumber]  = nowy.Disc.ToString();
                info[(int)TagFields.Year]        = nowy.Year.ToString();
                info[(int)TagFields.Genre]       = nowy.JoinedGenres;
                info[(int)TagFields.Comment]     = nowy.Comment;
                info[(int)TagFields.Composer]    = nowy.JoinedComposers;
                info[(int)TagFields.Cover]       = nowy.Pictures.Length.ToString();
                info[(int)TagFields.Tag]         = tablica.Last().Tag.GetType().ToString();
                info[(int)TagFields.BPM]         = nowy.BeatsPerMinute.ToString();

                int    j    = str.LastIndexOf("\\");        // znalezienie indeksu ostatniego slasha
                string file = "";
                string path = "";

                for (int i = j + 1; i < str.Length; i++)    // wczytanie nazwy pliku (od ostatniego slasha do końca)
                {
                    file += str[i];
                }

                for (int i = 0; i < j; i++)                 // wczytanie ścieżki pliku (od początku do ostatniego slasha)
                {
                    path += str[i];
                }

                info[(int)TagFields.Path]     = path;
                info[(int)TagFields.Filename] = file;

                mainGrid.Rows.Add(info);        // dodanie do głównego grida wszystkich informacji

                toolStripProgressBar1.Value++;  // zwiększenie wartości wczytanych plików
            }

            toolStripProgressBar1.Value = 0;        // wyzerowanie progress bara
        }
Esempio n. 18
0
        public async Task <string> saveArtwork(TagLib.Tag tag, int id)
        {
            IPicture   picture = tag.Pictures[0];
            ByteVector vector  = picture.Data;

            Byte[] bytes     = vector.ToArray();
            string extension = MimeTypesMap.GetExtension(picture.MimeType);

            System.IO.Directory.CreateDirectory(System.IO.Path.Combine(App.LocalStoragePath, "AlbumArt"));
            var filename = System.IO.Path.Combine(App.LocalStoragePath, "AlbumArt", id.ToString() + "." + extension);

            System.IO.File.WriteAllBytes(filename, bytes);
            return(id.ToString() + "." + extension);
        }
        /// <summary>
        /// Gets the Rating ("stars") of a given tag
        /// </summary>
        /// <param name="tag"></param>
        /// <returns></returns>
        public static PopularimeterFrame GetPopularimeterFrame(this Tag tag)
        {
            if (tag.TagTypes != TagTypes.Id3v2)
            {
                return(null);
            }

            TagLib.Id3v2.Tag.DefaultVersion      = 3;
            TagLib.Id3v2.Tag.ForceDefaultVersion = true;

            return(PopularimeterFrame.Get((TagLib.Id3v2.Tag)tag,
                                          "Windows Media Player 9 Series",
                                          true));
        }
Esempio n. 20
0
 public override TagLib.Tag GetTag(TagTypes type, bool create)
 {
     if (type != TagTypes.Apple)
     {
         return null;
     }
     if ((this.apple_tag == null) && create)
     {
         this.apple_tag = new AppleTag(this.udta_box);
         TagLib.Tag[] tags = new TagLib.Tag[] { this.apple_tag };
         this.tag.SetTags(tags);
     }
     return this.apple_tag;
 }
Esempio n. 21
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);
        }
Esempio n. 22
0
 private void GetInfoFromTag()
 {
     try 
     { 
         var tagFile = File.Create(FilePath); 
         Tag = tagFile.Tag;
         Duration = TimeSpan.FromSeconds((int)tagFile.Properties.Duration.TotalSeconds);
         Bitrate = tagFile.Properties.AudioBitrate;
         tagFile.Dispose();
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
 }
Esempio n. 23
0
        private static Tuple<LocalSong, byte[]> CreateSong(Tag tag, TimeSpan duration, string filePath)
        {
            var song = new LocalSong(filePath, duration)
            {
                Album = PrepareTag(tag.Album, String.Empty),
                Artist = PrepareTag(tag.FirstAlbumArtist ?? tag.FirstPerformer, "Unknown Artist"), //HACK: In the future retrieve the string for an unkown artist from the view if we want to localize it
                Genre = PrepareTag(tag.FirstGenre, String.Empty),
                Title = PrepareTag(tag.Title, Path.GetFileNameWithoutExtension(filePath)),
                TrackNumber = (int)tag.Track
            };

            IPicture picture = tag.Pictures.FirstOrDefault();

            return Tuple.Create(song, picture == null ? null : picture.Data.Data);
        }
Esempio n. 24
0
        public MidiFile(string name) : base("")
        {
            this.tag = new MidiTag();
            TagLib.Tag tag      = this.tag;
            char[]     chrArray = new char[] { '\\' };
            tag.Title = name.Split(chrArray).Last <string>();
            MediaPlayer mediaPlayer = new MediaPlayer();

            mediaPlayer.Open(new Uri(name));
            while (!mediaPlayer.NaturalDuration.HasTimeSpan)
            {
            }
            Duration naturalDuration = mediaPlayer.NaturalDuration;

            this.properties = new TagLib.Properties(naturalDuration.TimeSpan, new ICodec[0]);
        }
Esempio n. 25
0
 private void SetTag(TagLib.File File)
 {
     TagLib.Tag Tag = File.Tag;
     if (Tag != null)
     {
         this._Artist   = ConcatenateStrings(Tag.Performers);
         this._Album    = Tag.Album;
         this._Title    = Tag.Title;
         this._Track    = Tag.Track;
         this._Year     = Tag.Year;
         this._Comment  = Tag.Comment;
         this._Genre    = ConcatenateStrings(Tag.Genres);
         this._Bitrate  = File.Properties.AudioBitrate;
         this._Duration = File.Properties.Duration;
     }
 }
Esempio n. 26
0
        private static void CopyTags(Tag source, Tag target)
        {
            source.CopyTo(target, true);
            var l = source.Pictures.Length;
            var pictures = new IPicture[l];
            for (var i = 0; i < source.Pictures.Length; i++)
            {
                pictures[i] = new Picture(source.Pictures[i].Data)
                                  {
                                      MimeType = source.Pictures[i].MimeType,
                                      Description = source.Pictures[i].Description,
                                      Type = source.Pictures[i].Type
                                  };
            }

            target.Pictures = pictures;
        }
Esempio n. 27
0
		public Task WriteTags(CancellationToken ct, Stream stream, Tag tags)
		{
			Guard.ForNull(stream, nameof(stream));
			Guard.ForNull(tags, nameof(tags));
			return Task.Run(() =>
			{
				using (var fileAbstraction = new AlwaysOpenStreamFileAbstraction(_witnessFilename, stream))
				using (var file = TagLib.File.Create(fileAbstraction))
                {
					var fileTags = file.GetTag(_tagTypes, true);
					fileTags.Clear();
					tags.CopyTo(fileTags, true);
					fileTags.Pictures = tags.Pictures;
					file.Save();
				}
			});
		}
Esempio n. 28
0
 public static Tag Choose(Tag first, Tag second)
 {
     if (first == null)
     {
         if (second == null)
         {
             return null;
         }
         else
         {
             return second;
         }
     }
     else
     {
         return first;
     }
 }
Esempio n. 29
0
        private IOldTrack GetTrack(string path, TagLib.Tag tag)
        {
            var track = new OldTrack()
            {
                Path = path
            };

            if (!string.IsNullOrEmpty(tag.Title))
            {
                track.Title = tag.Title;
            }

            if (!string.IsNullOrEmpty(tag.Album))
            {
                track.Album = tag.Album;
            }

            track.TrackNumber = tag.Track;
            track.DiscNumber  = tag.Disc;

            if (!string.IsNullOrEmpty(tag.JoinedGenres))
            {
                track.Genre = tag.JoinedGenres;
            }

            if (!string.IsNullOrEmpty(tag.JoinedPerformers))
            {
                track.Artist = tag.JoinedPerformers;
            }

            if (tag.Year > 0 && tag.Year < int.MaxValue)
            {
                track.ReleaseDate = new DateTime((int)tag.Year, 1, 1);
            }

            if (tag.Pictures.Length > 0)
            {
                track.ImageData = tag.Pictures[0].Data;
            }

            track.Comment = tag.Comment;

            return(track);
        }
		public async Task Synchronize_ShouldCallSynchronize(
			[Frozen]Mock<IAsyncFileOperations> fileOperations,
			[Frozen]Mock<IAudioTagReader> audioTagReader,
			[Frozen]Mock<IAudioTagWriter> audioTagWriter,
			AudioTagsSynchronizer sut,
			SourceFilePath sourceFile,
			TargetFilePath targetFile,
			Stream sourceStream,
			Stream targetStream,
            Tag tag)
		{
			//arrange
			fileOperations.Setup(f => f.OpenRead(sourceFile.ToString())).ReturnsTask(sourceStream);
			fileOperations.Setup(f => f.Open(targetFile.ToString(), Hanno.IO.FileMode.Open, Hanno.IO.FileAccess.ReadWrite)).ReturnsTask(targetStream);
			audioTagReader.Setup(a => a.ReadTags(It.IsAny<CancellationToken>(), sourceStream)).ReturnsTask(tag);
			//act
			await sut.SynchronizeTags(CancellationToken.None, sourceFile.File, targetFile.File);
			//assert
			audioTagWriter.Verify(a => a.WriteTags(It.IsAny<CancellationToken>(), targetStream, tag));
        }
Esempio n. 31
0
 public static void CheckTags (Tag tag)
 {
     Assert.AreEqual ("TEST album", tag.Album);
     Assert.AreEqual ("TEST artist 1; TEST artist 2", tag.JoinedAlbumArtists);
     Assert.AreEqual (120, tag.BeatsPerMinute);
     Assert.AreEqual ("TEST comment", tag.Comment);
     Assert.AreEqual ("TEST composer 1; TEST composer 2", tag.JoinedComposers);
     Assert.AreEqual ("TEST conductor", tag.Conductor);
     Assert.AreEqual ("TEST copyright", tag.Copyright);
     Assert.AreEqual (100, tag.Disc);
     Assert.AreEqual (101, tag.DiscCount);
     Assert.AreEqual ("TEST genre 1; TEST genre 2", tag.JoinedGenres);
     Assert.AreEqual ("TEST grouping", tag.Grouping);
     Assert.AreEqual ("TEST lyrics 1\r\nTEST lyrics 2", tag.Lyrics);
     Assert.AreEqual ("TEST performer 1; TEST performer 2", tag.JoinedPerformers);
     Assert.AreEqual ("TEST title", tag.Title);
     Assert.AreEqual (98, tag.Track);
     Assert.AreEqual (99, tag.TrackCount);
     Assert.AreEqual (1999, tag.Year);
 }
Esempio n. 32
0
        public override TagLib.Tag GetTag(TagLib.TagTypes type, bool create)
        {
            TagLib.Tag tag = base.GetTag(type, false);
            if (tag != null)
            {
                return(tag);
            }
            if (!create || (type & ImageTag.AllowedTypes) == 0)
            {
                return(null);
            }
            if (type != TagTypes.TiffIFD)
            {
                return(base.GetTag(type, create));
            }
            ImageTag new_tag = new IFDTag(this);

            ImageTag.AddTag(new_tag);
            return(new_tag);
        }
Esempio n. 33
0
 public static void SetTags (Tag tag)
 {
     tag.Album = "TEST album";
     tag.AlbumArtists = new string [] {"TEST artist 1", "TEST artist 2"};
     tag.BeatsPerMinute = 120;
     tag.Comment = "TEST comment";
     tag.Composers = new string [] {"TEST composer 1", "TEST composer 2"};
     tag.Conductor = "TEST conductor";
     tag.Copyright = "TEST copyright";
     tag.Disc = 100;
     tag.DiscCount = 101;
     tag.Genres = new string [] {"TEST genre 1", "TEST genre 2"};
     tag.Grouping = "TEST grouping";
     tag.Lyrics = "TEST lyrics 1\r\nTEST lyrics 2";
     tag.Performers = new string [] {"TEST performer 1", "TEST performer 2"};
     tag.Title = "TEST title";
     tag.Track = 98;
     tag.TrackCount = 99;
     tag.Year = 1999;
 }
Esempio n. 34
0
 public XiphComment GetComment(bool create, Tag copy)
 {
     foreach (Tag tag in this.Tags)
     {
         if (tag is XiphComment)
         {
             return (tag as XiphComment);
         }
     }
     if (!create)
     {
         return null;
     }
     XiphComment target = new XiphComment();
     if (copy != null)
     {
         copy.CopyTo(target, true);
     }
     base.AddTag(target);
     return target;
 }
Esempio n. 35
0
        static void Main(string[] args)
        {
            try
            {
                TagLib.File file = TagLib.File.Create(@"D:\test.ogg");
                TagLib.Tag  tags = file.Tag;

                // Read some information.
                var title   = tags.Title;
                var artists = tags.Artists;                 // Remember, each song can have more than one artist.
                var album   = tags.Album;
                var genres  = tags.Genres;
                var year    = tags.Year;
                var track   = tags.Track;

                var composer = tags.Composers;

                Console.WriteLine("title : " + title);
                Console.Write("Atrists : ");
                foreach (string s in artists)
                {
                    Console.Write(s + ", ");
                }
                Console.WriteLine("\nAlbum : " + album);
                Console.Write("Genres : ");
                foreach (string s in genres)
                {
                    Console.Write(s + ", ");
                }
                Console.WriteLine("\nYear : " + year);
                Console.WriteLine("Track : " + track);
                Console.Write("Composers : ");
                foreach (string s in composer)
                {
                    Console.Write(s + ", ");
                }
            }
            catch (Exception e) { Console.WriteLine(e); }
        }
Esempio n. 36
0
        public void initTagInfo(Tag tag, string name)
        {
            this._album = tag.Album;

            //If array performers is null an error will be thrown trying to access the [0] element
            if (tag.Performers != null && tag.Performers.Length > 0)
            {
                this._artist = tag.Performers[0];
            }

            this._songName = name;

            if (tag.Genres != null && tag.Genres.Length > 0)
            {
                this._genre = tag.Genres[0];
            }

            this._composer = tag.FirstComposer;
            this._comment = tag.Comment;
            this._trackNumber = tag.Track;
            this._year = tag.Year;
            this._beatsPerMinute = tag.BeatsPerMinute;
        }
Esempio n. 37
0
        private static JsonObject GetAlbum(JsonObject library, TagLib.Tag tag)
        {
            JsonArray artists = library.GetNamedArray("artists");

            // create the array if it doesn't exist
            if (artists == null)
            {
                artists = new JsonArray();
                library.Add("artists", artists);
            }

            JsonObject matchedArtist = null;
            JsonObject matchedAlbum  = null;
            string     artistName    = "Unknown Artist";

            if (!string.IsNullOrEmpty(tag.FirstAlbumArtist))
            {
                artistName = tag.FirstAlbumArtist;
            }
            else if (!string.IsNullOrEmpty(tag.FirstArtist))
            {
                artistName = tag.FirstArtist;
            }
            else if (!string.IsNullOrEmpty(tag.FirstPerformer))
            {
                artistName = tag.FirstPerformer;
            }
            else if (!string.IsNullOrEmpty(tag.FirstComposer))
            {
                artistName = tag.FirstComposer;
            }

            foreach (JsonObject artist in artists.Select(x => x.GetObject()))
            {
                if (artist.GetNamedString("name") == artistName)
                {
                    matchedArtist = artist;
                }
            }

            // no artist found, create it
            if (matchedArtist == null)
            {
                matchedArtist = new JsonObject();
                matchedArtist.Add("name", JsonValue.CreateStringValue(artistName));
                matchedArtist.Add("albums", new JsonArray());
                artists.Add(matchedArtist);
            }

            // find the album
            JsonArray albums = matchedArtist.GetNamedArray("albums");

            // check to see if the albums array exists
            if (albums == null)
            {
                albums = new JsonArray();
                matchedArtist.Add("albums", albums);
            }

            // find the album
            foreach (JsonObject album in albums.Select(x => x.GetObject()))
            {
                if (album.GetNamedString("name") == tag.Album)
                {
                    matchedAlbum = album;
                }
            }

            // if the album wasn't found, create it
            if (matchedAlbum == null)
            {
                matchedAlbum = new JsonObject();
                matchedAlbum.Add("name", JsonValue.CreateStringValue(tag.Album));
                matchedAlbum.Add("tracks", new JsonArray());
                albums.Add(matchedAlbum);
            }

            return(matchedAlbum);
        }
Esempio n. 38
0
        /// <summary>
        ///     Get track metadata and save it to the library
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public async Task SaveTrackToLibrary(DriveItem item)
        {
            try
            {
                List <string> audioExtensions = new List <string>();
                audioExtensions.Add(".flac");
                audioExtensions.Add(".mp3");
                audioExtensions.Add(".m4a");

                object downloadURL = new object();
                if (audioExtensions.Contains(item.Name.Substring(item.Name.LastIndexOf("."), item.Name.Length - item.Name.LastIndexOf("."))))
                {
                    item.AdditionalData?.TryGetValue(@"@microsoft.graph.downloadUrl", out downloadURL);
                    PartialHTTPStream httpResponseStream = new PartialHTTPStream(downloadURL.ToString(), 100000);
                    TagLib.Tag        tag = AudioTagHelper.FileTagReader(httpResponseStream, "test" + item.Name.Substring(item.Name.LastIndexOf("."), item.Name.Length - item.Name.LastIndexOf(".")));


                    Track track = new Track();
                    track.Title       = tag.Title;
                    track.Year        = (int)tag.Year;
                    track.TrackNumber = (int)tag.Track;
                    track.DiscNumber  = (int)tag.Disc;
                    track.OneDrive_ID = item.Id;
                    track.FileName    = item.Name;
                    track.LastUpdate  = item.LastModifiedDateTime;


                    List <Track> tracks = (await App.Library.GetTrackByOneDrive_ID(item.Id));
                    if (tracks.Count() == 0 || tracks[0].LastUpdate < track.LastUpdate)
                    {
                        List <Artist> artists = await App.Library.GetArtistByName(tag.Artists.First());

                        if (artists.Count() == 0)
                        {
                            Artist artist = new Artist();
                            artist.Name = tag.Artists.First();
                            await App.Library.SaveArtist(artist);

                            track.Artist_ID = artist.ID;
                        }
                        else
                        {
                            track.Artist_ID = artists[0].ID;
                        }

                        List <Album> albums = await App.Library.GetAlbumByTitleAndAlbumArtist(tag.Album, (tag.AlbumArtists == null || tag.AlbumArtists.Length == 0 ? tag.Artists[0] : tag.AlbumArtists[0]));

                        if (albums.Count() == 0)
                        {
                            Album         album        = new Album();
                            Artist        albumArtist  = new Artist();
                            List <Artist> albumArtists = await App.Library.GetArtistByName((tag.AlbumArtists == null || tag.AlbumArtists.Length == 0 ? tag.Artists[0] : tag.AlbumArtists[0]));

                            if (albumArtists.Count() == 0)
                            {
                                albumArtist.Name = tag.AlbumArtists.First();
                                await App.Library.SaveArtist(albumArtist);

                                album.AlbumArtist_ID = albumArtist.ID;
                            }
                            else
                            {
                                album.AlbumArtist_ID = albumArtists.First().ID;
                            }
                            album.Title = tag.Album;
                            await App.Library.InsertAlbum(album);

                            album.ArtworkFile = await saveArtwork(tag, album.ID);

                            await App.Library.UpdateAlbum(album);

                            track.Album_ID = album.ID;
                        }
                        else
                        {
                            track.Album_ID = albums[0].ID;
                        }

                        if (tracks.Count() > 0 && tracks[0].LastUpdate < track.LastUpdate)
                        {
                            track.ID = tracks[0].ID;
                            await App.Library.UpdateTrack(track);
                        }
                        else
                        {
                            await App.Library.SaveTrack(track);
                        }
                    }
                }
            }
            catch (Exception e)
            {
            }
        }
Esempio n. 39
0
        private Guid GetArtist(Tag tag, ref Repository repo)
        {
            Guid id;
            lock (artistLock)
            {
                var artist = repo.Artists.FirstOrDefault(x => x.Name == tag.FirstArtist);
                if (artist == null)
                {
                    artist = new Artist {Id = Guid.NewGuid()};
                    artist.MBID = string.IsNullOrEmpty(tag.MusicBrainzArtistId) ? (Guid?) null : new Guid(tag.MusicBrainzArtistId);
                    artist.Name = tag.FirstArtist;
                    repo.Artists.InsertOnSubmit(artist);
                    repo.SubmitChanges();
                }
                id = artist.Id;
            }

            return id;
        }
Esempio n. 40
0
        public Song CreateSong(string filePath, int?folderId, TagLib.File file)
        {
            int?itemId = Injection.Kernel.Get <IItemRepository>().GenerateItemId(ItemType.Song);

            if (itemId == null)
            {
                return(new Song());
            }

            Song song = new Song();

            song.ItemId   = itemId;
            song.FolderId = folderId;

            // Parse taglib tags
            TagLib.Tag tag = file.Tag;

            try
            {
                string firstPerformer = tag.FirstPerformer;
                if (firstPerformer != null)
                {
                    Artist artist = Injection.Kernel.Get <IArtistRepository>().ArtistForNameOrCreate(firstPerformer.Trim());
                    song.ArtistId   = artist.ArtistId;
                    song.ArtistName = artist.ArtistName;
                }
            }
            catch (Exception e)
            {
                if (logger.IsErrorEnabled)
                {
                    logger.Error("Error creating artist info for song: ", e);
                }
                song.ArtistId   = null;
                song.ArtistName = null;
            }

            try
            {
                string firstAlbumArtist = tag.FirstAlbumArtist;
                if (firstAlbumArtist != null)
                {
                    AlbumArtist albumArtist = Injection.Kernel.Get <IAlbumArtistRepository>().AlbumArtistForNameOrCreate(firstAlbumArtist.Trim());
                    song.AlbumArtistId   = albumArtist.AlbumArtistId;
                    song.AlbumArtistName = albumArtist.AlbumArtistName;
                }
            }
            catch (Exception e)
            {
                if (logger.IsErrorEnabled)
                {
                    logger.Error("Error creating album artist info for song: ", e);
                }
                song.AlbumArtistId   = null;
                song.AlbumArtistName = null;
            }

            // If we have an artist, but not an albumArtist, then use the artist info for albumArtist
            if (song.AlbumArtistId == null && song.ArtistName != null)
            {
                AlbumArtist albumArtist = Injection.Kernel.Get <IAlbumArtistRepository>().AlbumArtistForNameOrCreate(song.ArtistName);
                song.AlbumArtistId   = albumArtist.AlbumArtistId;
                song.AlbumArtistName = albumArtist.AlbumArtistName;
            }

            try
            {
                string albumName = tag.Album;
                if (albumName != null)
                {
                    Album album = Injection.Kernel.Get <IAlbumRepository>().AlbumForName(albumName.Trim(), song.AlbumArtistId, Convert.ToInt32(tag.Year));
                    song.AlbumId     = album.AlbumId;
                    song.AlbumName   = album.AlbumName;
                    song.ReleaseYear = album.ReleaseYear;
                }
            }
            catch (Exception e)
            {
                if (logger.IsErrorEnabled)
                {
                    logger.Error("Error creating album info for song: ", e);
                }
                song.AlbumId     = null;
                song.AlbumName   = null;
                song.ReleaseYear = null;
            }

            song.FileType = song.FileType.FileTypeForTagLibMimeType(file.MimeType);

            if (song.FileType == FileType.Unknown)
            {
                logger.IfInfo("\"" + filePath + "\" Unknown file type: " + file.Properties.Description);
            }

            try
            {
                string title = tag.Title;
                if (title != null)
                {
                    song.SongName = title.Trim();
                }
            }
            catch
            {
                song.SongName = null;
            }

            try
            {
                song.TrackNumber = Convert.ToInt32(tag.Track);
            }
            catch
            {
                song.TrackNumber = null;
            }

            try
            {
                song.DiscNumber = Convert.ToInt32(tag.Disc);
            }
            catch
            {
                song.DiscNumber = null;
            }

            try
            {
                string firstGenre = tag.FirstGenre;
                if (firstGenre != null)
                {
                    song.GenreName = firstGenre.Trim();
                }
            }
            catch
            {
                song.GenreName = null;
            }

            try
            {
                song.BeatsPerMinute = tag.BeatsPerMinute;
            }
            catch
            {
                song.BeatsPerMinute = null;
            }

            try
            {
                song.Lyrics = tag.Lyrics;
            }
            catch
            {
                song.Lyrics = null;
            }

            try
            {
                song.Comment = tag.Comment;
            }
            catch
            {
                song.Comment = null;
            }

            // Dispose tag
            tag = null;

            if ((object)song.GenreName != null)
            {
                // Retreive the genre id
                song.GenreId = Injection.Kernel.Get <IGenreRepository>().GenreForName(song.GenreName).GenreId;
            }

            song.Duration = Convert.ToInt32(file.Properties.Duration.TotalSeconds);
            song.Bitrate  = file.Properties.AudioBitrate;

            // Get necessary filesystem information about file
            FileInfo fsFile = new FileInfo(filePath);

            song.FileSize     = fsFile.Length;
            song.LastModified = fsFile.LastWriteTime.ToUnixTime();
            song.FileName     = fsFile.Name;

            // If there is no song name, use the file name
            if (song.SongName == null || song.SongName == "")
            {
                song.SongName = song.FileName;
            }

            // Generate an art id from the embedded art, if it exists
            int?artId = CreateArt(file).ArtId;

            // Dispose file handles
            fsFile = null;
            file.Dispose();

            // If there was no embedded art, use the folder's art
            artId = (object)artId == null?Injection.Kernel.Get <IArtRepository>().ArtIdForItemId(song.FolderId) : artId;

            // Create the art/item relationship
            Injection.Kernel.Get <IArtRepository>().UpdateArtItemRelationship(artId, song.ItemId, true);

            return(song);
        }
Esempio n. 41
0
		/// <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="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>This method only copies the most basic values when
		///    copying between different tag formats, however, if
		///    <paramref name="target" /> is of the same type as the
		///    current instance, more advanced copying may be done.
		///    For example, <see cref="TagLib.Id3v2.Tag" /> will copy
		///    all of its frames to another tag.</para>
		/// </remarks>
		/// <exception cref="ArgumentNullException">
		///    <paramref name="target" /> is <see langword="null" />.
		/// </exception>
		public virtual void CopyTo (Tag target, bool overwrite)
		{
			if (target == null)
				throw new ArgumentNullException ("target");
			
			if (overwrite || IsNullOrLikeEmpty (target.Title))
				target.Title = Title;
			
			if (overwrite || IsNullOrLikeEmpty (target.AlbumArtists))
				target.AlbumArtists = AlbumArtists;
			
			if (overwrite || IsNullOrLikeEmpty (target.Performers))
				target.Performers = Performers;
			
			if (overwrite || IsNullOrLikeEmpty (target.Composers))
				target.Composers = Composers;
			
			if (overwrite || IsNullOrLikeEmpty (target.Album))
				target.Album = Album;
			
			if (overwrite || IsNullOrLikeEmpty (target.Comment))
				target.Comment = Comment;
			
			if (overwrite || IsNullOrLikeEmpty (target.Genres))
				target.Genres = Genres;
			
			if (overwrite || target.Year == 0)
				target.Year = Year;
			
			if (overwrite || target.Track == 0)
				target.Track = Track;
			
			if (overwrite || target.TrackCount == 0)
				target.TrackCount = TrackCount;
			
			if (overwrite || target.Disc == 0)
				target.Disc = Disc;
			
			if (overwrite || target.DiscCount == 0)
				target.DiscCount = DiscCount;
			
			if (overwrite || target.BeatsPerMinute == 0)
				target.BeatsPerMinute = BeatsPerMinute;
			
			if (overwrite || IsNullOrLikeEmpty (target.Grouping))
				target.Grouping = Grouping;
			
			if (overwrite || IsNullOrLikeEmpty (target.Conductor))
				target.Conductor = Conductor;
			
			if (overwrite || IsNullOrLikeEmpty (target.Copyright))
				target.Copyright = Copyright;
		}
Esempio n. 42
0
        private Guid GetAlbum(Guid artistId, Tag tag, ref Repository repo)
        {
            Guid id;
            lock (albumLock)
            {
                var album = repo.Albums.FirstOrDefault(x => x.ArtistId == artistId && x.Name == tag.Album);
                if (album == null)
                {
                    album = new Album {Id = Guid.NewGuid()};
                    album.MBID = string.IsNullOrEmpty(tag.MusicBrainzReleaseId) ? (Guid?) null : new Guid(tag.MusicBrainzReleaseId);
                    album.Name = tag.Album;
                    album.ArtistId = artistId;
                    repo.Albums.InsertOnSubmit(album);
                    repo.SubmitChanges();
                }
                id = album.Id;
            }

            return id;
        }
Esempio n. 43
0
        protected override void DoPullProperties()
        {
            TagLib.File file;

            try {
                file = TagLib.File.Create(new StreamAbstraction(Stream), GetTaglibMimeType(), TagLib.ReadStyle.Average);
            } catch (Exception e) {
                Logger.Log.Warn(e, "Exception filtering music");
                Finished();
                return;
            }

            TagLib.Tag tag = file.Tag;

            AddProperty(Beagle.Property.New("fixme:album", tag.Album));
            AddProperty(Beagle.Property.New("dc:title", tag.Title));

            foreach (string artist in tag.AlbumArtists)
            {
                AddProperty(Beagle.Property.New("fixme:artist", artist));
            }

            foreach (string performer in tag.Performers)
            {
                AddProperty(Beagle.Property.New("fixme:performer", performer));
            }

            foreach (string composer in tag.Composers)
            {
                AddProperty(Beagle.Property.New("fixme:composer", composer));
            }

            foreach (string genre in tag.Genres)
            {
                AddProperty(Beagle.Property.New("fixme:genre", genre));
            }

            AddProperty(Beagle.Property.New("fixme:comment", tag.Comment));

            if (tag.Track > 0)
            {
                AddProperty(Beagle.Property.NewUnsearched("fixme:tracknumber", tag.Track));
            }

            if (tag.TrackCount > 0)
            {
                AddProperty(Beagle.Property.NewUnsearched("fixme:trackcount", tag.TrackCount));
            }

            if (tag.Disc > 0)
            {
                AddProperty(Beagle.Property.NewUnsearched("fixme:discnumber", tag.Disc));
            }

            if (tag.DiscCount > 0)
            {
                AddProperty(Beagle.Property.NewUnsearched("fixme:disccount", tag.DiscCount));
            }

            if (tag.Year > 0)
            {
                AddProperty(Beagle.Property.NewUnsearched("fixme:year", tag.Year));
            }

            foreach (TagLib.ICodec codec in file.Properties.Codecs)
            {
                TagLib.IAudioCodec acodec = codec as TagLib.IAudioCodec;

                if (acodec != null && (acodec.MediaTypes & TagLib.MediaTypes.Audio) != TagLib.MediaTypes.None)
                {
                    AddProperty(Beagle.Property.NewUnsearched("fixme:bitrate", acodec.AudioBitrate));
                    AddProperty(Beagle.Property.NewUnsearched("fixme:samplerate", acodec.AudioSampleRate));
                    AddProperty(Beagle.Property.NewUnsearched("fixme:channels", acodec.AudioChannels));
                    // One codec is enough
                    break;
                }
                // FIXME: Get data from IVideoCodec too
            }

            if (file.Properties.MediaTypes != TagLib.MediaTypes.None)
            {
                AddProperty(Beagle.Property.NewUnsearched("fixme:duration", file.Properties.Duration));
            }

            // FIXME: Store embedded picture and lyrics

            Finished();
        }
Esempio n. 44
0
        private void GetTagInformation(String m_filename)
        {
            //get information
            TagLib.Tag tag = TagLib.File.Create(m_filename).Tag;
            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.DecodePixelHeight = 50;
                        albumImage.DecodePixelWidth  = 50;
                        albumImage.EndInit();
                        ImageAlbumArt.Source = albumImage.Clone();
                        using (MemoryStream albumArtworkMemStream2 = new MemoryStream(tag.Pictures[0].Data.Data))
                        {
                            BitmapImage albumImage2 = new BitmapImage();
                            albumImage2.BeginInit();
                            albumImage2.CacheOption       = BitmapCacheOption.OnLoad;
                            albumImage2.StreamSource      = albumArtworkMemStream2;
                            albumImage2.DecodePixelHeight = 200;
                            albumImage2.DecodePixelWidth  = 200;
                            albumImage2.EndInit();
                            ImageAlbumArtBig.Source = albumImage2;
                            albumArtworkMemStream2.Close();
                        }
                        _storyboard.Begin(ImageAlbumArtBig);
                    }
                    catch (NotSupportedException)
                    {
                        ImageAlbumArt.Source = null;
                    }
                    albumArtworkMemStream.Close();
                }
            }
            else
            {
                ImageAlbumArt.Source = null;
            }

            string   blankspace = "    ";
            TAG_INFO info       = new TAG_INFO(m_filename);

            if (BassTags.BASS_TAG_GetFromFile(_stream, info))
            {
                LabelTitle.Content     = info.title;
                LabelArtist.Content    = info.artist;
                LabelTitleForCard.Text = info.title;
                LabelAlbumForCard.Text = info.album;
                System.Text.StringBuilder albumtext = new System.Text.StringBuilder();
                albumtext.Append(info.artist);
                albumtext.Append(" ");
                albumtext.Append(info.year);
                LabelArtistForCard.Text = albumtext.ToString();
                albumtext.Remove(0, albumtext.Length);
                albumtext.Append("   比特率");
                albumtext.Append(blankspace);
                albumtext.Append(info.bitrate);
                albumtext.Append("kbps");
                ListViewItemBit.Content = albumtext;
                System.Text.StringBuilder n_rating = new System.Text.StringBuilder();
                n_rating.Append("   采样率");
                n_rating.Append(blankspace);
                n_rating.Append("44.100");
                ListViewItemRate.Content = n_rating;
            }
            else
            {
                var tfile = TagLib.File.Create(m_filename);
                LabelTitle.Content     = tfile.Tag.Title;
                LabelArtist.Content    = tfile.Tag.Performers[0];
                LabelTitleForCard.Text = tfile.Tag.Title;
                LabelAlbumForCard.Text = tfile.Tag.Album;
                System.Text.StringBuilder albumtext = new System.Text.StringBuilder();
                albumtext.Append(tfile.Tag.Performers[0]);
                albumtext.Append(" ");
                albumtext.Append(tfile.Tag.Year);
                LabelArtistForCard.Text = tfile.Tag.Performers[0];
                albumtext.Remove(0, albumtext.Length);
                albumtext.Append("   比特率");
                albumtext.Append(blankspace);
                albumtext.Append(tfile.Properties.AudioBitrate);
                albumtext.Append("kbps");
                ListViewItemBit.Content = albumtext;
                System.Text.StringBuilder n_rating = new System.Text.StringBuilder();
                n_rating.Append("   采样率");
                n_rating.Append(blankspace);
                n_rating.Append(String.Format("{0:##,###}", tfile.Properties.AudioSampleRate));
                ListViewItemRate.Content = n_rating;
                PlayList memberData = new PlayList();
                memberData.Title  = tfile.Tag.Title;
                memberData.Artist = tfile.Tag.Performers[0];
                memberData.Album  = tfile.Tag.Album;

                this.tb1.Items.Add(memberData);
            }

            FileInfo _fileinfo = new FileInfo(info.filename);

            System.Text.StringBuilder n_writetime = new System.Text.StringBuilder();
            n_writetime.Append("修改时间");
            n_writetime.Append(blankspace);
            n_writetime.Append(_fileinfo.CreationTime);
            ListViewItemWriteTime.Content = n_writetime;
            System.Text.StringBuilder n_addtime = new System.Text.StringBuilder();
            n_addtime.Append("添加时间");
            n_addtime.Append(blankspace);
            n_addtime.Append(_fileinfo.LastWriteTime);
            ListViewItemAddTime.Content = n_addtime;
            System.Text.StringBuilder n_filesize = new System.Text.StringBuilder();
            string _filesize = _fileinfo.Length / 1024 / 1024 + "." + Math.Round((double)(_fileinfo.Length / 1024 % 1024 / 10), 2) + "MB";

            n_filesize.Append("文件大小");
            n_filesize.Append(blankspace);
            n_filesize.Append(_filesize);
            ListViewItemFileSize.Content = n_filesize;
            System.Text.StringBuilder n_filepath = new System.Text.StringBuilder();
            n_filepath.Append("文件位置");
            n_filepath.Append(blankspace);
            n_filepath.Append(_fileinfo.DirectoryName);
            ListViewItemFilePath.Content = n_filepath;
        }
 protected void InsertTag(int index, Tag tag)
 {
     this.tags.Insert(index, tag);
 }
 protected void RemoveTag(Tag tag)
 {
     this.tags.Remove(tag);
 }
 protected void AddTag(Tag tag)
 {
     this.tags.Add(tag);
 }
        /// <summary>
        ///    Gets a specified picture frame from the specified tag,
        ///    optionally creating it if it does not exist.
        /// </summary>
        /// <param name="tag">
        ///    A <see cref="Tag" /> object to search in.
        /// </param>
        /// <param name="description">
        ///    A <see cref="string" /> specifying the description to
        ///    match.
        /// </param>
        /// <param name="type">
        ///    A <see cref="PictureType" /> specifying the picture type
        ///    to match.
        /// </param>
        /// <param name="create">
        ///    A <see cref="bool" /> specifying whether or not to create
        ///    and add a new frame to the tag if a match is not found.
        /// </param>
        /// <returns>
        ///    A <see cref="AttachedPictureFrame" /> object containing
        ///    the matching frame, or <see langword="null" /> if a match
        ///    wasn't found and <paramref name="create" /> is <see
        ///    langword="false" />.
        /// </returns>
        /// <example>
        ///    <para>Sets a cover image with a description. Because <see
        ///    cref="Get(Tag,string,PictureType,bool)" /> is used, if
        ///    the program is called again with the same audio file and
        ///    desciption, the picture will be overwritten with the new
        ///    one.</para>
        ///    <code lang="C#">
        /// using TagLib;
        /// using TagLib.Id3v2;
        ///
        /// public static class SetId3v2Cover
        /// {
        /// 	public static void Main (string [] args)
        /// 	{
        /// 		if (args.Length != 3)
        /// 			throw new ApplicationException (
        /// 				"USAGE: SetId3v2Cover.exe AUDIO_FILE PICTURE_FILE DESCRIPTION");
        ///
        /// 		// Create the file. Can throw file to TagLib# exceptions.
        /// 		File file = File.Create (args [0]);
        ///
        /// 		// Get or create the ID3v2 tag.
        /// 		TagLib.Id3v2.Tag tag = file.GetTag (TagTypes.Id3v2, true) as TagLib.Id3v2.Tag;
        /// 		if (tag == null)
        /// 			throw new ApplicationException ("File does not support ID3v2 tags.");
        ///
        /// 		// Create a picture. Can throw file related exceptions.
        ///		TagLib.Picture picture = TagLib.Picture.CreateFromPath (args [1]);
        ///
        /// 		// Get or create the picture frame.
        /// 		AttachedPictureFrame frame = AttachedPictureFrame.Get (
        /// 			tag, args [2], PictureType.FrontCover, true);
        ///
        /// 		// Set the data from the picture.
        /// 		frame.MimeType = picture.MimeType;
        /// 		frame.Data     = picture.data;
        /// 		
        /// 		// Save the file.
        /// 		file.Save ();
        /// 	}
        /// }
        ///    </code>
        /// </example>
        public static AttachedPictureFrame Get(Tag tag,
            string description,
            PictureType type,
            bool create)
        {
            AttachedPictureFrame apic;
            foreach (Frame frame in tag.GetFrames (FrameType.APIC)) {
                apic = frame as AttachedPictureFrame;

                if (apic == null)
                    continue;

                if (description != null && apic.Description != description)
                    continue;

                if (type != PictureType.Other && apic.Type != type)
                    continue;

                return apic;
            }

            if (!create)
                return null;

            apic = new AttachedPictureFrame ();
            apic.Description = description;
            apic.Type = type;

            tag.AddFrame (apic);

            return apic;
        }
Esempio n. 49
0
        private void Obtener_Tag(string ruta)
        {
            TagLib.File PistaMp3 = TagLib.File.Create(ruta);

            try { indice = PistaMp3.Tag.Track.Equals(0) ? indice = Buscar_Indice(Titulo) : indice = (int)PistaMp3.Tag.Track; }
            catch { indice = 0; }

            try
            {
                if (!PistaMp3.Tag.Title.Equals(string.Empty))
                    Titulo = PistaMp3.Tag.Title;
            }
            catch
            {
                Titulo = string.Empty;
            }

            try
            {
                CaratulaAlbum = Image.FromStream(new MemoryStream(PistaMp3.Tag.Pictures.ToList().Find(x => x.Type.ToString() == "FrontCover").Data.Data));
            }
            catch
            {
                CaratulaAlbum = null;
            }

            tagCancion = PistaMp3.Tag;
            propiedades = PistaMp3.Properties;

            PistaMp3.Dispose();
        }
Esempio n. 50
0
        protected override void DoPullProperties()
        {
            TagLib.File file = null;

            try {
                file = TagLib.File.Create(new StreamAbstraction(Stream), GetTaglibMimeType(), TagLib.ReadStyle.Average);
            } catch (Exception e) {
                Logger.Log.Warn(e, "Exception filtering video");
                Finished();
                return;
            }

            TagLib.Tag tag = file.Tag;

            // FIXME: Most likely most of these don't make sense
            // for video files.

            AddProperty(Beagle.Property.New("dc:title", tag.Title));
            AddProperty(Beagle.Property.New("fixme:album", tag.Album));

            foreach (string artist in tag.AlbumArtists)
            {
                AddProperty(Beagle.Property.New("fixme:artist", artist));
            }

            foreach (string performer in tag.Performers)
            {
                AddProperty(Beagle.Property.New("fixme:performer", performer));
            }

            foreach (string composer in tag.Composers)
            {
                AddProperty(Beagle.Property.New("fixme:composer", composer));
            }

            foreach (string genre in tag.Genres)
            {
                AddProperty(Beagle.Property.New("fixme:genre", genre));
            }

            AddProperty(Beagle.Property.New("fixme:comment", tag.Comment));

            if (tag.Track > 0)
            {
                AddProperty(Beagle.Property.NewUnsearched("fixme:tracknumber", tag.Track));
            }

            if (tag.TrackCount > 0)
            {
                AddProperty(Beagle.Property.NewUnsearched("fixme:trackcount", tag.TrackCount));
            }

            if (tag.Disc > 0)
            {
                AddProperty(Beagle.Property.NewUnsearched("fixme:discnumber", tag.Disc));
            }

            if (tag.DiscCount > 0)
            {
                AddProperty(Beagle.Property.NewUnsearched("fixme:disccount", tag.DiscCount));
            }

            if (tag.Year > 0)
            {
                AddProperty(Beagle.Property.NewUnsearched("fixme:year", tag.Year));
            }

            foreach (TagLib.ICodec codec in file.Properties.Codecs)
            {
                TagLib.IVideoCodec vcodec = codec as TagLib.IVideoCodec;

                if (vcodec != null && (vcodec.MediaTypes & TagLib.MediaTypes.Video) != TagLib.MediaTypes.None)
                {
                    AddProperty(Beagle.Property.NewUnsearched("fixme:video:codec", vcodec.Description));
                    AddProperty(Beagle.Property.NewUnsearched("fixme:video:width", vcodec.VideoWidth));
                    AddProperty(Beagle.Property.NewUnsearched("fixme:video:height", vcodec.VideoHeight));

                    // One codec is enough
                    break;
                }
            }

            if (file.Properties.MediaTypes != TagLib.MediaTypes.None)
            {
                AddProperty(Beagle.Property.NewUnsearched("fixme:duration", file.Properties.Duration));
            }

            Finished();
        }
 private File SaveToFile(File file, Tag tag)
 {
     if (Id3Handler.Save(file, _file))
     {
         if (checkBoxRename.Checked)
         {
             var filename =
                 Helper.RenameFile(new BaseInfoTag(tag.JoinedPerformers, tag.FirstPerformer, tag.Album,
                     tag.Title,
                     _file.Name));
             if (filename != Actiontype.Exception.ToString() &&
                 filename != Actiontype.Already.ToString())
                 return File.Create(filename);
         }
         return file;
     }
     return null;
 }
Esempio n. 52
0
        public void OnTag (string id, IEnumerable<Resource> resources, Tag tag, Action<Object> consumer)
        {
            var genres = tag.Genres;
            var artists = tag.Performers;
            var album_artists = tag.AlbumArtists;
            var composers = tag.Composers;

            var music_track = new MusicTrack (id, Wmp11Ids.AllMusic, new MusicTrackOptions {
                Title = tag.Title,
                OriginalTrackNumber = (int)tag.Track,
                Genres = genres,
                Artists = GetArtists (artists),
                Resources = resources
            });

            audio_items.Add (music_track);
            consumer (music_track);

            foreach (var genre in genres) {
                genre_builder.OnItem (genre, music_track, consumer,
                    options => options != null ? options : new GenreOptions { Title = genre });
            }

            foreach (var artist in artists) {
                artist_builder.OnItem (artist, music_track, consumer,
                    options => ArtistWithGenres (artist, genres, options));
            }

            album_builder.OnItem (tag.Album, music_track, consumer,
                options => options != null ? options : new MusicAlbumOptions {
                    Title = tag.Album,
                    Contributors = album_artists
                });

            foreach (var album_artist in album_artists) {
                album_artist_builder.OnItem (album_artist, music_track, consumer,
                    options => ArtistWithGenres (album_artist, genres, options));
            }

            foreach (var composer in composers) {
                composer_builder.OnItem (composer, music_track, consumer,
                    options => ArtistWithGenres (composer, genres, options));
            }
        }
Esempio n. 53
0
        public async Task AddSongAsync(Song song, Tag tags = null)
        {
            var primaryArtist = (song.Album == null ? song.Artist : song.Album.PrimaryArtist)
                                ?? new Artist {Name = "Unknown Artist", ProviderId = "autc.unknown"};
            var artist =
                _inProgressArtists.Union(Artists).FirstOrDefault(
                    entry =>
                        entry.ProviderId == primaryArtist.ProviderId
                        || string.Equals(entry.Name, primaryArtist.Name, StringComparison.CurrentCultureIgnoreCase));
            if (artist == null)
            {
                await _sqlService.InsertAsync(primaryArtist);
                _inProgressArtists.Add(primaryArtist);

                song.Artist = primaryArtist;
                song.ArtistId = primaryArtist.Id;

                if (song.Album != null)
                {
                    song.Album.PrimaryArtistId = song.Artist.Id;
                    song.Album.PrimaryArtist = song.Artist;
                }
            }
            else
            {
                song.Artist = artist;

                if (song.Album != null)
                {
                    song.Album.PrimaryArtistId = artist.Id;
                    song.Album.PrimaryArtist = artist;
                }
            }

            song.ArtistId = song.Artist.Id;

            if (song.Album == null)
            {
                song.Album = new Album
                {
                    PrimaryArtistId = song.ArtistId,
                    Name = song.Name,
                    PrimaryArtist = song.Artist,
                    ProviderId = "autc.single." + song.ProviderId
                };
            }

            var album = _inProgressAlbums.Union(Albums).FirstOrDefault(p => p.ProviderId == song.Album.ProviderId);

            if (album != null)
            {
                song.Album = album;
            }
            else
            {
                await _sqlService.InsertAsync(song.Album);
                _inProgressAlbums.Add(song.Album);
                await _dispatcher.RunAsync(() =>
                {
                    var artwork = song.Artist.HasArtwork
                                    ? song.Artist.Artwork
                                    : _missingArtwork;
                    song.Album.Artwork = artwork;
                    song.Album.MediumArtwork = artwork;
                    song.Album.SmallArtwork = artwork;
                });

                if (tags != null && tags.Pictures != null && tags.Pictures.Length > 0)
                {
                    var albumFilePath = string.Format(_artworkFilePath, song.Album.Id);
                    Stream artwork = null;

                    var image = tags.Pictures.FirstOrDefault();
                    if (image != null)
                    {
                        artwork = new MemoryStream(image.Data.Data);
                    }

                    if (artwork != null)
                    {
                        using (artwork)
                        {
                            try
                            {
                                var file =
                                    await
                                        StorageHelper.CreateFileAsync(
                                            albumFilePath,
                                            option: CreationCollisionOption.ReplaceExisting);

                                using (var fileStream = await file.OpenAsync(FileAccess.ReadAndWrite))
                                {
                                    var bytes = tags.Pictures[0].Data.Data;
                                    await fileStream.WriteAsync(bytes, 0, bytes.Length);
                                    song.Album.HasArtwork = true;
                                    await _sqlService.UpdateItemAsync(song.Album);
                                }
                            }
                            catch
                            {
                                // ignored
                            }
                        }
                    }

                    // set it
                    if (song.Album.HasArtwork)
                    {
                        await _dispatcher.RunAsync(
                            () =>
                            {
                                var path = _localFilePrefix + albumFilePath;

                                song.Album.Artwork = _bitmapFactory.CreateImage(new Uri(path));

                                if (ScaledImageSize == 0)
                                {
                                    return;
                                }

                                song.Album.Artwork.SetDecodedPixel(ScaledImageSize);

                                song.Album.MediumArtwork = _bitmapFactory.CreateImage(new Uri(path));
                                song.Album.MediumArtwork.SetDecodedPixel(ScaledImageSize/2);

                                song.Album.SmallArtwork = _bitmapFactory.CreateImage(new Uri(path));
                                song.Album.SmallArtwork.SetDecodedPixel(50);
                            });
                    }
                }
            }

            song.AlbumId = song.Album.Id;

            if (string.IsNullOrEmpty(song.ArtistName)) song.ArtistName = song.Artist.Name;

            await _sqlService.InsertAsync(song);

            await _dispatcher.RunAsync(
                () =>
                {
                    if (!song.IsTemp)
                    {
                        var orderedAlbumSong = song.Album.Songs.ToList();
                        orderedAlbumSong.Add(song);
                        orderedAlbumSong = orderedAlbumSong.OrderBy(p => p.TrackNumber).ToList();

                        var index = orderedAlbumSong.IndexOf(song);
                        song.Album.Songs.Insert(index, song);


                        var orderedArtistSong = song.Artist.Songs.ToList();
                        orderedArtistSong.Add(song);
                        orderedArtistSong = orderedArtistSong.OrderBy(p => p.Name).ToList();

                        index = orderedArtistSong.IndexOf(song);
                        song.Artist.Songs.Insert(index, song);

                        #region Order artist album

                        if (!song.Artist.Albums.Contains(song.Album))
                        {
                            var orderedArtistAlbum = song.Artist.Albums.ToList();
                            orderedArtistAlbum.Add(song.Album);
                            orderedArtistAlbum = orderedArtistAlbum.OrderBy(p => p.Name).ToList();

                            index = orderedArtistAlbum.IndexOf(song.Album);
                            song.Artist.Albums.Insert(index, song.Album);
                        }

                        #endregion
                    }

                    _inProgressAlbums.Remove(song.Album);
                    _inProgressArtists.Remove(song.Artist);

                    if (!Albums.Contains(song.Album))
                        Albums.Add(song.Album);
                    else if (song.Album.Songs.Count == 1)
                    {
                        // This means the album was added with a temp song
                        // Have to remove and readd it to get it to show up
                        Albums.Remove(song.Album);
                        Albums.Add(song.Album);
                    }

                    if (!Artists.Contains(song.Artist))
                        Artists.Add(song.Artist);
                    else if (song.Artist.Songs.Count == 1)
                    {
                        // This means the album was added with a temp song
                        // Have to remove and readd it to get it to show up
                        Artists.Remove(song.Artist);
                        Artists.Add(song.Artist);
                    }

                    Songs.Add(song);
                });
        }