示例#1
0
 public MpegAudio(string path)
 {
     this.ResetData();
     using (BinaryReader reader1 = new BinaryReader(File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)))
     {
         int num1 = ID3v2Helper.GetTagSize(reader1.BaseStream);
         this.m_FileLength = reader1.BaseStream.Length;
         reader1.BaseStream.Seek((long)num1, SeekOrigin.Begin);
         byte[] buffer1 = reader1.ReadBytes(0xd82);
         this.FindFrame(buffer1, ref this.m_VBR);
         this.m_VendorID = this.FindVendorID(buffer1);
         if (!this.m_Frame.Found)
         {
             reader1.BaseStream.Seek((this.m_FileLength - num1) / ((long)2), SeekOrigin.Begin);
             buffer1 = reader1.ReadBytes(0xd82);
             this.FindFrame(buffer1, ref this.m_VBR);
         }
         if (this.m_Frame.Found && string.IsNullOrEmpty(this.m_VendorID))
         {
             reader1.BaseStream.Seek((long)-(buffer1.Length + ID3v1Helper.GetTagSize(reader1.BaseStream)), SeekOrigin.End);
             buffer1 = reader1.ReadBytes(0xd82);
             this.FindFrame(buffer1, ref this.m_VBR);
             this.m_VendorID = this.FindVendorID(buffer1);
         }
     }
     if (!this.m_Frame.Found)
     {
         this.ResetData();
     }
 }
示例#2
0
        private void btnRemoveID3v2_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(m_Filename))
            {
                MessageBox.Show("No file loaded", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                DialogResult result = MessageBox.Show(String.Format("Remove ID3v2 tag from '{0}'?", Path.GetFileName(m_Filename)), "", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    Boolean success = ID3v2Helper.RemoveTag(m_Filename);
                    if (success)
                    {
                        MessageBox.Show("ID3v2 tag successfully removed", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("ID3v2 tag not found", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }

            btnRemoveID3v2.Enabled = ID3v2Helper.DoesTagExist(m_Filename);
            ucID3v2.LoadFile(m_Filename);
        }
示例#3
0
        public void LoadFile(String path)
        {
            ClearImageData();

            m_ID3v2 = ID3v2Helper.CreateID3v2(path);

            txtFilename.Text    = Path.GetFileName(path);
            txtArtist.Text      = m_ID3v2.Artist;
            txtTitle.Text       = m_ID3v2.Title;
            txtAlbum.Text       = m_ID3v2.Album;
            cmbGenre.Text       = m_ID3v2.Genre;
            txtYear.Text        = m_ID3v2.Year;
            txtTrackNumber.Text = m_ID3v2.TrackNumber;

            BindingSource bindingSource = new BindingSource();

            imageBindingNavigator.BindingSource = bindingSource;
            bindingSource.CurrentChanged       += new EventHandler(bindingSource_CurrentChanged);
            bindingSource.DataSource            = m_ID3v2.PictureList;

            switch (m_ID3v2.Header.TagVersion)
            {
            case ID3v2TagVersion.ID3v22:
                cmbID3v2.SelectedIndex = cmbID3v2.Items.IndexOf("ID3v2.2");
                break;

            case ID3v2TagVersion.ID3v23:
                cmbID3v2.SelectedIndex = cmbID3v2.Items.IndexOf("ID3v2.3");
                break;

            case ID3v2TagVersion.ID3v24:
                cmbID3v2.SelectedIndex = cmbID3v2.Items.IndexOf("ID3v2.4");
                break;
            }
        }
示例#4
0
        private void LoadFile(String path)
        {
            m_Filename = path;

            ucID3v2.LoadFile(m_Filename);
            ucID3v1.LoadFile(m_Filename);

            btnSave.Enabled        = true;
            btnRemoveID3v2.Enabled = ID3v2Helper.DoesTagExist(m_Filename);
            btnRemoveID3v1.Enabled = ID3v1Helper.DoesTagExist(m_Filename);
        }
示例#5
0
        /// <summary>
        /// This method sets various audio file properties into a Dictionary
        /// </summary>
        /// <param name="source">source indicates the path to the file whose properties are to be extracted</param>
        /// <returns>Returns a Dictionary object where key => property name and value => property value</returns>
        public override StringDictionary GetProperties(string source)
        {
            if (IO.File.Exists(source))
            {
                try
                {
                    TagLib.File file = TagLib.File.Create(source);
                    TagLib.Tag  tags = file.Tag;

                    fileProperties["title"]   = tags.Title;
                    fileProperties["album"]   = tags.Album;
                    fileProperties["artist"]  = string.Join(",", tags.AlbumArtists);
                    fileProperties["year"]    = tags.Year.ToString();
                    fileProperties["track"]   = tags.Track.ToString();
                    fileProperties["genres"]  = string.Join(",", tags.Genres);
                    fileProperties["comment"] = tags.Comment;
                    fileProperties["length"]  = TimeSpan.Parse(file.Properties.Duration.Hours + ":" + file.Properties.Duration.Minutes + ":" + file.Properties.Duration.Seconds).ToString();
                }
                catch (Exception ex) //CorruptFileException
                {
                    if (ID3v1Helper.DoesTagExist(source))
                    {
                        IID3v1 id3v1 = ID3v1Helper.CreateID3v1(source);
                        fileProperties["title"]   = id3v1.Title;
                        fileProperties["album"]   = id3v1.Album;
                        fileProperties["artist"]  = id3v1.Artist;
                        fileProperties["year"]    = id3v1.Year;
                        fileProperties["track"]   = id3v1.TrackNumber.ToString();
                        fileProperties["comment"] = id3v1.Comment;
                    }
                    if (ID3v2Helper.DoesTagExist(source))
                    {
                        IID3v2   id3v2 = ID3v2Helper.CreateID3v2(source);
                        TimeSpan ts    = TimeSpan.FromMilliseconds(id3v2.LengthMilliseconds.Value);
                        fileProperties["length"] = TimeSpan.Parse(ts.Hours + ":" + ts.Minutes + ":" + ts.Seconds).ToString();
                        fileProperties["genres"] = id3v2.Genre;
                    }
                    if (!(ID3v1Helper.DoesTagExist(source) && ID3v2Helper.DoesTagExist(source)))
                    {
                        RemoveFileSpecificKeys();
                    }
                }
                return(base.GetProperties(source));
            }
            else if (Win32Helper.PathExist(source))
            {
                RemoveFileSpecificKeys(); return(base.GetProperties(source));
            }
            return(null);
        }
示例#6
0
        private void ScanDirectory(Object basePathObject)
        {
            Int32 totalFiles = 0;
            BindingList <Track> trackList = new BindingList <Track>();

            try
            {
                String basePath = (String)basePathObject;

                DirectoryInfo di       = new DirectoryInfo(basePath);
                FileInfo[]    fileList = di.GetFiles("*.mp3", SearchOption.AllDirectories);

                EnableCancelButton();

                totalFiles = fileList.Length;

                for (Int32 i = 0; i < totalFiles; i++)
                {
                    if (m_CancelScanning)
                    {
                        totalFiles = i;
                        break;
                    }

                    IID3v2 id3 = ID3v2Helper.CreateID3v2(fileList[i].FullName);

                    trackList.Add(new Track(id3.Artist, id3.Title, id3.Album, id3.Year, id3.Genre, fileList[i].Name));

                    if ((i % 100) == 0)
                    {
                        UpdateProgress(i * 100 / totalFiles);
                    }
                }
            }
            finally
            {
                EndRecursiveScanning(totalFiles, trackList);
            }
        }
示例#7
0
        /*
         * private void LoadImageData(IAttachedPicture attachedPicture)
         * {
         * pictureBox1.Image = attachedPicture.Picture;
         *
         * txtImageDescription.Text = attachedPicture.Description;
         * cmbImageType.SelectedIndex = cmbImageType.Items.IndexOf(PictureTypeHelper.GetStringFromPictureType(attachedPicture.PictureType));
         *
         * txtImageDescription.Enabled = true;
         * cmbImageType.Enabled = true;
         * }
         *
         * private void ClearImageData()
         * {
         * pictureBox1.Image = null;
         * txtImageDescription.Text = "";
         * cmbImageType.SelectedIndex = -1;
         *
         * txtImageDescription.Enabled = false;
         * cmbImageType.Enabled = false;
         * }
         *
         * private void SaveImageToFile(IAttachedPicture attachedPicture)
         * {
         * String extension = attachedPicture.PictureExtension;
         *
         * imageSaveFileDialog.FileName = "image." + extension;
         *
         * DialogResult dialogResult = imageSaveFileDialog.ShowDialog();
         * if (dialogResult == DialogResult.OK)
         * {
         * using (FileStream fs = File.Open(imageSaveFileDialog.FileName, FileMode.Create, FileAccess.Write, FileShare.None))
         * {
         *  fs.Write(attachedPicture.PictureData, 0, attachedPicture.PictureData.Length);
         * }
         * }
         * }
         *
         * private void LoadImageFromFile(IAttachedPicture attachedPicture)
         * {
         * DialogResult dialogResult = imageOpenFileDialog.ShowDialog();
         * if (dialogResult == DialogResult.OK)
         * {
         * attachedPicture.Picture = Image.FromFile(imageOpenFileDialog.FileName);
         * pictureBox1.Image = attachedPicture.Picture;
         * }
         * }
         *
         * private IAttachedPicture GetCurrentPictureFrame()
         * {
         * if (imageBindingNavigator.BindingSource == null)
         * return null;
         * return imageBindingNavigator.BindingSource.Current as IAttachedPicture;
         * }
         */
        #endregion <<< Private Methods >>>


        #region <<< Public Methods >>>

        public void LoadFile(FileInfo file)
        {
            m_ID3v2   = ID3v2Helper.CreateID3v2(file.FullName);
            m_tagdict = new StringDictionary();
            m_tagdict.Add("MP3FileName", file.Name);

            PropertyInfo[] infos = this.m_ID3v2.GetType().GetProperties();

            foreach (PropertyInfo info in infos)
            {
                m_tagdict.Add(info.Name, String.Format("{0}", info.GetValue(this.m_ID3v2, null)));
            }
            switch (m_ID3v2.Header.TagVersion)
            {
            case ID3v2TagVersion.ID3v22:
                break;

            case ID3v2TagVersion.ID3v23:
                break;

            case ID3v2TagVersion.ID3v24:
                break;
            }
        }
示例#8
0
        private void AddMusic(string[] strTemp, string strTitle, string strFileName, string strFilePath)
        {
            bool isFolder      = false;
            bool isEmptyFolder = false;

            FileInfo  file     = new FileInfo(Path.Combine(strFilePath, strFileName));
            Hashtable tags     = new Hashtable();
            Media     objMedia = MediaServices.Get(_strMediaName.Trim(), _mediaType, _path, _cleanTitle, _entityType, _patternType, _useSubFolder, _bGetImage, _bParseNfo, true);

            if (file.Exists == false && string.IsNullOrWhiteSpace(file.Extension))
            {
                if (Directory.Exists(file.FullName))
                {
                    DirectoryInfo folder = new DirectoryInfo(file.FullName);

                    FileInfo[] files = folder.GetFiles("*.mp3", SearchOption.TopDirectoryOnly);
                    files = files.Concat(folder.GetFiles("*.flc", SearchOption.TopDirectoryOnly)).ToArray();
                    files = files.Concat(folder.GetFiles("*.flac", SearchOption.TopDirectoryOnly)).ToArray();

                    if (files.Any())
                    {
                        file     = files[0];
                        isFolder = true;
                    }
                    else
                    {
                        isEmptyFolder = true;
                    }
                }
            }

            if (isEmptyFolder == false)
            {
                if (Dal.GetInstance.GetMusics(objMedia.Name, strFilePath, strFileName) == null)
                {
                    switch (file.Extension)
                    {
                    case ".mp3":
                        IID3v2 objMp3Tag = ID3v2Helper.CreateID3v2(file.FullName);

                        tags.Add("Title", objMp3Tag.Title);


                        if (string.IsNullOrWhiteSpace(objMp3Tag.Album) == false)
                        {
                            tags.Add("Album", objMp3Tag.Album);
                        }

                        if (isFolder == false && objMp3Tag.LengthMilliseconds != null)
                        {
                            tags.Add("Length", objMp3Tag.LengthMilliseconds);
                        }

                        if (objMp3Tag.PictureList.Count > 0)
                        {
                            tags.Add("Cover", objMp3Tag.PictureList[0].PictureData);
                        }

                        tags.Add("Genre", objMp3Tag.Genre);
                        tags.Add("Artist", objMp3Tag.Artist);
                        break;

                    case ".flac":
                    case ".flc":
                        try
                        {
                            FlacTagger objFlacTag = new FlacTagger(file.FullName);

                            tags.Add("Title", objFlacTag.Title);

                            if (string.IsNullOrWhiteSpace(objFlacTag.Album) == false)
                            {
                                tags.Add("Album", objFlacTag.Album);
                            }

                            if (isFolder == false)
                            {
                                tags.Add("Length", objFlacTag.Length);
                            }

                            if (objFlacTag.Arts.Count > 0)
                            {
                                tags.Add("Cover", objFlacTag.Arts[0].PictureData);
                            }

                            tags.Add("Genre", objFlacTag.Genre);
                            tags.Add("Artist", objFlacTag.Artist);
                            break;
                        }
                        //FIX 2.8.9.0
                        catch (FileFormatException)
                        {
                            break;
                        }
                    }

                    #region Title

                    if (tags.ContainsKey("Title") == false)
                    {
                        if (string.IsNullOrEmpty(strTitle) == false)
                        {
                            strTitle = strTitle.Replace('_', ' ');
                            strTitle = strTitle.Replace(".MP3", "");
                            strTitle = strTitle.Replace(".Mp3", "");
                            strTitle = strTitle.Replace(".flac", "");
                            strTitle = strTitle.Trim();
                            strTitle = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(strTitle);
                            tags.Add("Title", strTitle);
                        }
                    }

                    #endregion

                    Music objMusic = new Music();
                    objMusic.Ressources = new List <Ressource>();
                    objMusic.Genres     = new List <Genre>();
                    objMusic.Title      = strTitle;
                    objMusic.AddedDate  = DateTime.Now;
                    objMusic.FileName   = strFileName;
                    objMusic.FilePath   = strFilePath;

                    if (tags.ContainsKey("Album"))
                    {
                        objMusic.Album = tags["Album"].ToString();
                        if (isFolder == true && string.IsNullOrWhiteSpace(tags["Album"].ToString()) == false)
                        {
                            objMusic.Title = tags["Album"].ToString();
                        }
                    }

                    if (tags.ContainsKey("Length"))
                    {
                        objMusic.Runtime = tags["Length"] as int?;
                    }

                    objMusic.Media = objMedia;

                    #region Cover

                    if (_bGetImage == true)
                    {
                        RessourcesServices.AddImage(Util.GetLocalImage(objMusic.FilePath, objMusic.FileName, _bFile), objMusic,
                                                    true);
                    }
                    else
                    {
                        RessourcesServices.AddImage(tags["Cover"] as byte[], objMusic, true);
                    }

                    #endregion

                    bool bExist = false;
                    if (Dal.GetInstance.GetMusics(objMusic.Media.Name, objMusic.FilePath, objMusic.FileName) != null)
                    {
                        bExist = true;
                    }

                    if (bExist == false)
                    {
                        #region ParseNfo

                        if (_bParseNfo == true)
                        {
                            string errorMessage;
                            MusicServices.ParseNfo(objMusic, out errorMessage);
                        }
                        #endregion
                        #region Artist
                        string strArtistFullName = string.Empty;
                        if (tags.ContainsKey("Artist") == true)
                        {
                            if (tags["Artist"] == null)
                            {
                                if (_mapping != null)
                                {
                                    strArtistFullName = Util.ConstructString(strTemp, (string[])_mapping["Artist"], _nbrBaseParsing);
                                }
                            }
                            else
                            {
                                strArtistFullName = tags["Artist"] as string;
                            }
                        }
                        #endregion
                        Dal.GetInstance.AddMusic(objMusic);
                        if (tags.ContainsKey("Genre"))
                        {
                            GenreServices.AddGenres(new[] { tags["Genre"] as string }, objMusic, true);
                        }
                        if (strArtistFullName != null && string.IsNullOrWhiteSpace(strArtistFullName.Trim()) == false)
                        {
                            ArtistServices.AddArtist(strArtistFullName, objMusic);
                        }

                        _intAddedItem++;
                    }
                    else
                    {
                        _intNotAddedItem++;
                    }
                }
            }
        }
示例#9
0
        public void SyncTagsToFiles()
        {
            using (var dataContext = new MusicEntities1())
            {
                IQueryable <SONG> songs     = dataContext.SONG.OrderByDescending(s => s.UPDATED).Take(5000);
                SONG[]            songArray = songs.ToArray();

                foreach (SONG song in songArray)
                {
                    try
                    {
                        if (Regex.IsMatch(song.LOCATION, ".mp3", RegexOptions.IgnoreCase))
                        {
                            FileInfo fileInfo      = new FileInfo(song.LOCATION);
                            string   directoryRoot = Directory.GetDirectoryRoot(song.LOCATION);
                            string   filename      = song.LOCATION;
                            if (directoryRoot.ToLower().IndexOf("e:\\") == -1)
                            {
                                filename = filename.Substring(1);
                                filename = "e" + filename;
                            }

                            string genre = null;

                            IID3v2 iD3v2 = ID3v2Helper.CreateID3v2(filename);
                            genre = iD3v2.Genre;

                            UltraID3 ultraID3 = new UltraID3();
                            ultraID3.Read(filename);
                            if (string.IsNullOrWhiteSpace(genre))
                            {
                                genre = ultraID3.Genre;
                            }
                            else if (ultraID3.Genre != genre)
                            {
//                                ultraID3.Genre = genre;
                            }

                            IID3v1 iD3v1 = ID3v1Helper.CreateID3v1(filename);
                            if (Regex.IsMatch(genre, "("))
                            {
                                genre = GenreHelper.GenreByIndex[iD3v1.GenreIndex];
                            }

//                            ID3v2Tag id3v2Tag = ultraID3.ID3v2Tag;


                            if ((genre != song.GENRE) &&
                                (!string.IsNullOrWhiteSpace(song.GENRE))
                                //&& (song.GENRE.ToLower().IndexOf("blues")==-1)
                                //&& (song.GENRE.ToLower().IndexOf("other") == -1)
                                //&& (song.GENRE.ToLower().IndexOf("unknown") == -1)
                                )
                            {
                                testContextInstance.WriteLine("{0}, DB genre: {1}, Disk genre: {2}", filename, song.GENRE, genre);

                                try
                                {
                                    ultraID3.Genre = song.GENRE;
                                    iD3v2.Genre    = song.GENRE;
                                }
                                catch (Exception e1)
                                {
                                    testContextInstance.WriteLine("Exception, song: {0}, {1}, {2}", song.LOCATION, e1.Message, e1.StackTrace);
                                }

                                iD3v2.Save(filename);
                                ultraID3.Write();
                            }
                        }
                    }
                    catch (System.IO.DirectoryNotFoundException)
                    {
                        testContextInstance.WriteLine("Exception, file not found, song: {0}", song.LOCATION);
                    }
                    catch (System.IO.FileNotFoundException)
                    {
                        testContextInstance.WriteLine("Exception, file not found, song: {0}", song.LOCATION);
                    }
                    catch (Exception ex)
                    {
                        testContextInstance.WriteLine("Exception, song: {0}, {1}, {2}", song.LOCATION, ex.Message, ex.StackTrace);
                    }
                }
            }
        }
示例#10
0
        public void SyncTagsToDb()
        {
            using (var dataContext = new MusicEntities1())
            {
                IQueryable <SONG> songs = from s in dataContext.SONG
                                          orderby s.ID
                                          select s;

                foreach (SONG song in songs)
                {
                    try
                    {
                        if (Regex.IsMatch(song.LOCATION, ".mp3", RegexOptions.IgnoreCase))
                        {
                            FileInfo fileInfo      = new FileInfo(song.LOCATION);
                            string   directoryRoot = Directory.GetDirectoryRoot(song.LOCATION);
                            string   filename      = song.LOCATION;
                            if (directoryRoot.ToLower().IndexOf("e:\\") == -1)
                            {
                                filename = filename.Substring(1);
                                filename = "e" + filename;
                            }

                            string genre = null;

                            UltraID3 ultraID3 = new UltraID3();
                            ultraID3.Read(filename);

                            genre = ultraID3.Genre;

                            IID3v2 iD3v2 = ID3v2Helper.CreateID3v2(filename);

                            if (string.IsNullOrWhiteSpace(genre))
                            {
                                genre = iD3v2.Genre;
                            }

                            IID3v1 iD3v1 = ID3v1Helper.CreateID3v1(filename);
                            if (string.IsNullOrWhiteSpace(genre))
                            {
                                genre = GenreHelper.GenreByIndex[iD3v1.GenreIndex];
                            }

                            ID3v2Tag id3v2Tag = ultraID3.ID3v2Tag;

                            //if ((!string.IsNullOrEmpty(ultraID3.Genre)) &&
                            //    (!string.IsNullOrEmpty(id3v2Tag.Genre)) &&
                            //    (ultraID3.Genre != id3v2Tag.Genre)
                            //    )
                            //{
                            //    testContextInstance.WriteLine("{0}, {1}", ultraID3.Genre, id3v2Tag.Genre);
                            //}

                            //genre = id3v2Tag.Genre;

                            //if (string.IsNullOrWhiteSpace(genre))
                            //{
                            //    genre = ultraID3.Genre;
                            //}

                            //if (!string.IsNullOrWhiteSpace(ultraID3.Genre))
                            //{
                            //    genre = ultraID3.Genre;
                            //}

                            //if (string.IsNullOrWhiteSpace(genre))
                            //{
                            //    genre = id3v2Tag.Genre;
                            //}


                            if ((genre != song.GENRE) &&
                                (!string.IsNullOrWhiteSpace(song.GENRE))
                                //&& (song.GENRE.ToLower().IndexOf("blues")==-1)
                                //&& (song.GENRE.ToLower().IndexOf("other") == -1)
                                //&& (song.GENRE.ToLower().IndexOf("unknown") == -1)
                                )
                            {
                                testContextInstance.WriteLine("{0}, DB genre: {1}, Disk genre: {2}", filename, song.GENRE, genre);

                                try
                                {
                                    if ((song.UPDATED > fileInfo.LastWriteTime) &&
                                        (song.GENRE != "Other"))
                                    {
                                        id3v2Tag.Genre = song.GENRE;
                                        ultraID3.Write();
                                    }
                                    else if (genre != "Other")
                                    {
                                        song.GENRE = genre;
                                    }
                                }
                                catch (Exception e1)
                                {
                                    testContextInstance.WriteLine("Exception, song: {0}, {1}, {2}", song.LOCATION, e1.Message, e1.StackTrace);
                                }
                            }
                        }
                    }
                    catch (System.IO.DirectoryNotFoundException)
                    {
                        testContextInstance.WriteLine("Exception, file not found, song: {0}", song.LOCATION);
                    }
                    catch (System.IO.FileNotFoundException)
                    {
                        testContextInstance.WriteLine("Exception, file not found, song: {0}", song.LOCATION);
                    }
                    catch (Exception ex)
                    {
                        testContextInstance.WriteLine("Exception, song: {0}, {1}, {2}", song.LOCATION, ex.Message, ex.StackTrace);
                    }
                }
                dataContext.SaveChanges();
            }
        }
示例#11
0
        public static SONG Populate(this SONG song)
        {
            string title, artist, album, genre;

            title  = null;
            artist = null;
            album  = null;
            genre  = null;
            string trackNumber = null;

            try
            {
                try
                {
                    IID3v2 iD3v2 = ID3v2Helper.CreateID3v2(song.LOCATION);
                    artist      = iD3v2.Artist;
                    title       = iD3v2.Title;
                    album       = iD3v2.Album;
                    genre       = iD3v2.Genre;
                    trackNumber = iD3v2.TrackNumber;
                    if ((!string.IsNullOrWhiteSpace(genre)) && (genre.Contains("(")))
                    {
                        genre = genre.Replace('(', ' ');
                        genre = genre.Replace(')', ' ');
                        genre = genre.Trim();
                        int genreIndex = Convert.ToInt16(genre);
                        genre = GenreHelper.GenreByIndex[genreIndex];
                    }
                }
                catch (Exception)
                {
                    Debug.WriteLine(String.Format("Warning: Unable to extract ID3v2 tags from {0}", song.LOCATION));
                }

                try
                {
                    IID3v1 iD3v1 = ID3v1Helper.CreateID3v1(song.LOCATION);
                    if ((string.IsNullOrWhiteSpace(genre)) || (genre.Contains("(")))
                    {
                        genre = GenreHelper.GenreByIndex[iD3v1.GenreIndex];
                    }
                    if (string.IsNullOrWhiteSpace(artist))
                    {
                        artist = iD3v1.Artist;
                    }
                    if (string.IsNullOrWhiteSpace(title))
                    {
                        title = iD3v1.Title;
                    }
                    if (string.IsNullOrWhiteSpace(album))
                    {
                        album = iD3v1.Album;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(string.Format("Warning: Unable to extract ID3v1 tags from {0} {1}", song.LOCATION, ex.Message));
                }

                if (String.IsNullOrWhiteSpace(title))
                {
                    String[] s = song.LOCATION.Split(new char[] { '\\', '.' });
                    title = s[s.Length - 2];
                }

                if (string.IsNullOrEmpty(artist))
                {
                    int loc = title.IndexOf("by");
                    if ((loc > -1) && (title.Length > 3))
                    {
                        artist = title.Substring(loc + 3);
                        if (loc > 1)
                        {
                            title = title.Substring(0, loc - 1);
                        }

                        loc = artist.IndexOf("from");
                        if ((loc > -1) && (artist.Length > 5))
                        {
                            album  = artist.Substring(loc + 5);
                            artist = artist.Substring(0, loc - 1);
                        }
                    }
                }

                song.TITLE       = title;
                song.ARTIST      = artist;
                song.GENRE       = genre;
                song.ALBUM       = album;
                song.TrackNumber = trackNumber;

                song.RATING = 1;

                try
                {
                    song.HASH = MusicDao.GenerateHashCode(song.LOCATION);
                }
                catch (Exception)
                {
                    Debug.WriteLine(String.Format("Warning: Unable to generate hash for {0}", song.LOCATION));
                }

                try
                {
                    FileInfo fileInfo = new FileInfo(song.LOCATION);
                    song.FILESIZE = fileInfo.Length;
                }
                catch (Exception)
                {
                    Debug.WriteLine(String.Format("Warning: Unable to get file length {0}", song.LOCATION));
                }
            }
            catch (Exception e1)
            {
                Debug.WriteLine(e1.Message);
            }

            return(song);
        }
示例#12
0
        public void UpdateTags(string connectionString, string musicDrive)
        {
            int songId    = 0;
            int batchSize = 100;

            while (true)
            {
                bool songTaken = false;
                using (var dataContext = new MusicEntities1())
                {
                    IQueryable <SONG> songs = dataContext.SONG.Where(s => s.ID > songId && s.LOCATION.ToLower().Contains(".mp3")).OrderBy(s => s.ID).Take(batchSize);

                    foreach (SONG song in songs)
                    {
                        songTaken = true;
                        try
                        {
                            FileInfo fileInfo      = new FileInfo(song.LOCATION);
                            string   directoryRoot = Directory.GetDirectoryRoot(song.LOCATION);
                            string   filename      = song.LOCATION;
                            if (directoryRoot.ToLower().IndexOf(musicDrive) != 0)
                            {
                                filename = filename.Substring(1);
                                filename = musicDrive + filename;
                            }
                            string genre = null;

                            UltraID3 ultraID3 = new UltraID3();
                            ultraID3.Read(filename);

                            genre = ultraID3.Genre;

                            IID3v2 iD3v2 = ID3v2Helper.CreateID3v2(filename);

                            if (string.IsNullOrWhiteSpace(genre))
                            {
                                genre = iD3v2.Genre;
                            }

                            IID3v1 iD3v1 = ID3v1Helper.CreateID3v1(filename);
                            if (string.IsNullOrWhiteSpace(genre))
                            {
                                genre = GenreHelper.GenreByIndex[iD3v1.GenreIndex];
                            }

                            ID3v2Tag id3v2Tag = ultraID3.ID3v2Tag;

                            if ((genre != song.GENRE) &&
                                (!string.IsNullOrWhiteSpace(song.GENRE)) &&
                                (song.GENRE.ToLower().IndexOf("blues") == -1) &&
                                (song.GENRE.ToLower().IndexOf("other") == -1) &&
                                (song.GENRE.ToLower().IndexOf("unknown") == -1)
                                )
                            {
                                Console.WriteLine(String.Format("{0}, DB genre: {1}, Disk genre: {2}", filename, song.GENRE, genre));

                                try
                                {
                                    ultraID3.Genre = song.GENRE;
                                }
                                catch (Exception e1)
                                {
                                    Console.WriteLine(String.Format("Exception, song: {0}, {1}, {2}", song.LOCATION, e1.Message, e1.StackTrace));
                                }

                                id3v2Tag.Genre = song.GENRE;
                                ultraID3.Write();
                            }
                        }
                        catch (System.IO.DirectoryNotFoundException)
                        {
                            Console.WriteLine(String.Format("Exception, file not found, song: {0}", song.LOCATION));
                        }
                        catch (System.IO.FileNotFoundException)
                        {
                            Console.WriteLine(String.Format("Exception, file not found, song: {0}", song.LOCATION));
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(String.Format("Exception, song: {0}, {1}, {2}", song.LOCATION, ex.Message, ex.StackTrace));
                        }
                        songId = song.ID;
                    }
                }
                if (!songTaken)
                {
                    break;
                }
            }
        }
示例#13
0
        public static void UpdateId3(Music objEntity)
        {
            string path = string.Empty;

            if (string.IsNullOrWhiteSpace(objEntity.FilePath) == false && string.IsNullOrWhiteSpace(objEntity.FileName) == false)
            {
                path = Path.Combine(objEntity.FilePath, objEntity.FileName);
            }
            else if (string.IsNullOrWhiteSpace(objEntity.FilePath) == true && string.IsNullOrWhiteSpace(objEntity.FileName) == false)
            {
                path = objEntity.FileName;
            }
            else if (string.IsNullOrWhiteSpace(objEntity.FilePath) == false && string.IsNullOrWhiteSpace(objEntity.FileName) == true)
            {
                path = objEntity.FilePath;
            }

            if (string.IsNullOrWhiteSpace(path) == false)
            {
                if (Directory.Exists(path))
                {
                    int    index;
                    byte[] cover = RessourcesServices.GetDefaultCover(objEntity, out index);

                    DirectoryInfo folder = new DirectoryInfo(path);

                    FileInfo[] files = folder.GetFiles("*.mp3", SearchOption.TopDirectoryOnly);
                    files = files.Concat(folder.GetFiles("*.flc", SearchOption.TopDirectoryOnly)).ToArray();
                    files = files.Concat(folder.GetFiles("*.flac", SearchOption.TopDirectoryOnly)).ToArray();

                    if (files.Any())
                    {
                        foreach (FileInfo file in files)
                        {
                            switch (file.Extension)
                            {
                            case ".mp3":
                                IID3v2 objMp3Tag = ID3v2Helper.CreateID3v2(file.FullName);
                                if (objMp3Tag != null)
                                {
                                    objMp3Tag.Album         = objEntity.Album;
                                    objMp3Tag.Artist        = objEntity.Artists.First().FulleName;
                                    objMp3Tag.Accompaniment = objEntity.Artists.First().FulleName;

                                    Genre genre = objEntity.Genres.FirstOrDefault();
                                    if (genre != null)
                                    {
                                        objMp3Tag.Genre = genre.DisplayName;
                                    }


                                    if (cover != null)
                                    {
                                        while (objMp3Tag.PictureList.Any())
                                        {
                                            objMp3Tag.PictureList.Remove(objMp3Tag.PictureList[0]);
                                        }

                                        IAttachedPicture picture = objMp3Tag.PictureList.AddNew();
                                        if (picture != null)
                                        {
                                            picture.PictureData = cover;
                                            picture.PictureType = PictureType.CoverFront;     // optional
                                        }
                                    }
                                    objMp3Tag.Save(file.FullName);
                                }
                                break;

                            case ".flac":
                            case ".flc":
                                FlacTagger flacTaggerTag = new FlacTagger(file.FullName);
                                flacTaggerTag.Album     = objEntity.Album;
                                flacTaggerTag.Artist    = objEntity.Artists.First().FulleName;
                                flacTaggerTag.Performer = objEntity.Artists.First().FulleName;

                                Genre musicGenre = objEntity.Genres.FirstOrDefault();
                                if (musicGenre != null)
                                {
                                    flacTaggerTag.Genre = musicGenre.DisplayName;
                                }


                                if (cover != null)
                                {
                                    while (flacTaggerTag.Arts.Any())
                                    {
                                        flacTaggerTag.RemoveArt(flacTaggerTag.Arts[0]);
                                    }

                                    ID3PictureFrame picture = new ID3PictureFrame(cover, ID3PictureType.FrontCover);
                                    flacTaggerTag.AddArt(picture);
                                }
                                flacTaggerTag.SaveMetadata();
                                break;
                            }
                        }
                    }
                }
            }
        }
示例#14
0
        public BasicLameTagReader(string path)
        {
            this.m_IsLameTagFound = true;
            this.m_Tag            = new LameTag();
            using (BinaryReader reader1 = new BinaryReader(File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)))
            {
                int num1 = ID3v2Helper.GetTagSize(reader1.BaseStream);
                reader1.BaseStream.Seek((long)num1, SeekOrigin.Begin);
                StartOfFile file1 = StartOfFile.FromBinaryReader(reader1);
                reader1.BaseStream.Seek((long)num1, SeekOrigin.Begin);
                string text1 = Encoding.ASCII.GetString(file1.Info1);
                string text2 = Encoding.ASCII.GetString(file1.Info2);
                string text3 = Encoding.ASCII.GetString(file1.Info3);
                switch (text1)
                {
                case "Xing":
                case "Info":
                    reader1.BaseStream.Seek((long)13, SeekOrigin.Current);
                    break;

                default:
                    switch (text2)
                    {
                    case "Xing":
                    case "Info":
                        reader1.BaseStream.Seek((long)0x15, SeekOrigin.Current);
                        break;
                    }
                    switch (text3)
                    {
                    case "Xing":
                    case "Info":
                        reader1.BaseStream.Seek((long)0x24, SeekOrigin.Current);
                        break;
                    }
                    this.m_IsLameTagFound = true;
                    break;
                }
                reader1.BaseStream.Seek((long)0x77, SeekOrigin.Current);
                this.m_Tag = LameTag.FromBinaryReader(reader1);
                reader1.BaseStream.Seek((long)-Marshal.SizeOf(typeof(LameTag)), SeekOrigin.Current);
                OldLameHeader header1 = OldLameHeader.FromBinaryReader(reader1);
                this.m_VersionStringNonLameTag = Encoding.ASCII.GetString(header1.VersionString);
            }
            if (this.m_Tag.VersionString[1] == 0x2e)
            {
                byte[] buffer1 = new byte[6];
                int    num2    = 0;
                while ((num2 < 4) || ((num2 == 4) && (this.m_Tag.VersionString[num2] == 0x62)))
                {
                    buffer1[num2] = this.m_Tag.VersionString[num2];
                    num2++;
                }
                Array.Resize <byte>(ref buffer1, num2);
                this.m_VersionString = Encoding.ASCII.GetString(buffer1);
            }
            else
            {
                this.m_VersionString = "";
            }
            if (Encoding.ASCII.GetString(this.m_Tag.Encoder) != "LAME")
            {
                this.m_IsLameTagFound = false;
            }
            this.m_Preset      = (ushort)(((this.m_Tag.Surround_Preset[0] << 8) + this.m_Tag.Surround_Preset[1]) & 0x7ff);
            this.m_PresetGuess = new PresetGuesser().GuessPreset(this.VersionStringNonLameTag, this.m_Tag.Bitrate, this.m_Tag.Quality, this.m_Tag.TagRevision_EncodingMethod, this.m_Tag.NoiseShaping, this.m_Tag.StereoMode, this.m_Tag.EncodingFlags_ATHType, this.m_Tag.Lowpass, out this.m_IsPresetGuessNonBitrate);
        }