Example #1
0
        public mp3(string filename)
        {
            isValidMp3   = false;
            errorMessage = "";

            // Parsing

            UltraID3 mp3 = new UltraID3();

            try
            {
                mp3.Read(filename);

                mp3Title  = mp3.Title;
                mp3Artist = mp3.Artist;
                mp3Album  = mp3.Album;
                mp3Genre  = mp3.Genre;
                mp3Length = (int)Math.Round(mp3.Duration.TotalSeconds);

                isValidMp3 = true;
            }
            catch (Exception e)
            {
                errorMessage = e.Message;
                nsGlobalOutput.output.write("Error: " + e.Message);
                return;
            }

            return;
        }
Example #2
0
 public frmProperties(IWMPMedia media)
 {
     InitializeComponent();
     myMp3.Read(media.sourceURL);
     this.Text = "Properties - " + media.name;
     fi        = new FileInfo(media.sourceURL);
     //File name
     setItem("File name", fi.Name, 0);
     //Folder name
     setItem("Folder name", fi.DirectoryName, 0);
     //File path
     setItem("File Path", fi.FullName, 0);
     //Size
     setItem("Size", String.Format("{0:0.00}", fi.Length * 0.000001) + " MB " + "(" + fi.Length.ToString("### ### ### ###") + " bytes)", 0);
     //Last moddified
     setItem("Last moddified", fi.LastWriteTimeUtc.ToString(), 0);
     //Duration
     setItem("Duration", media.durationString + " (" + media.duration.ToString() + " samples)", 1);
     //Bitrate
     setItem("Bitrate", Convert.ToInt32(media.getItemInfo("BitRate")) / 1000 + " kbps", 1);
     //Title
     setItem("Title", media.getItemInfo("title"), 1);
     //Genre
     setItem("Genre", myMp3.Genre, 1);
     //Album
     setItem("Album", media.getItemInfo("album"), 1);
     //Artist
     setItem("Artist", media.getItemInfo("artist"), 1);
     //Copyright
     setItem("Copyright", media.getItemInfo("copyright"), 1);
     //Track number
     setItem("Track number", myMp3.TrackNum.ToString(), 1);
     //MD5
     setItem("Audio MD5", GetMD5HashFromFile(media.sourceURL), 1);
 }
Example #3
0
        public Task ProcessAsync(ICrawler crawler, PropertyBag propertyBag)
        {
            if (propertyBag.StatusCode != HttpStatusCode.OK)
            {
                return(Task.CompletedTask);
            }

            using (var tempFile = new TempFile())
            {
                using (var fs = new FileStream(tempFile.FileName, FileMode.Create, FileAccess.Write, FileShare.Read, 0x1000))
                    using (var input = propertyBag.GetResponse())
                    {
                        input.CopyTo(fs);
                    }

                var id3 = new UltraID3();
                id3.Read(tempFile.FileName);

                propertyBag["MP3_Album"].Value    = id3.Album;
                propertyBag["MP3_Artist"].Value   = id3.Artist;
                propertyBag["MP3_Comments"].Value = id3.Comments;
                propertyBag["MP3_Duration"].Value = id3.Duration;
                propertyBag["MP3_Genre"].Value    = id3.Genre;
                propertyBag["MP3_Title"].Value    = id3.Title;
            }

            return(Task.CompletedTask);
        }
Example #4
0
        // triggered when Add button is pushed in GUI, after this all available tags are extracted from the audio files
        private void UserView_AddButtonPushed(IViewGUI sender) // sender is the object of Form1 class, through which we can access public properties
        {
            FilePathForController = sender.FilePaths;          // receive FilePaths from Form1 via public Property file path which is defined in IView Interface.
            FileNameForController = sender.FileNames;          // receive FileName from Form1 class / GUI for Title, if its abasent
            int k = 0;                                         // iterator thgough filenames for Title

            for (int i = 0; i < FilePathForController.Length; i++)
            {
                UltraID3 myMp3 = new UltraID3(); // initialize Tag class (external reference)
                try
                {
                    myMp3.Read(FilePathForController[i]);
                    // if there is no titles in the Tag then substitute it with file name of the audio file
                    if (myMp3.Title == "")
                    {
                        sender.Title = FileNameForController[k].Substring(0, FileNameForController[k].IndexOf('.')); // extract file name without extension (.mp3)
                        k++;
                    }
                    else
                    {
                        sender.Title = string.Format("{0}", myMp3.Title); // send the extracted tag/Title to the Form1 class
                    }
                    sender.Year   = string.Format("{0}", myMp3.Year);     // send all tags to the Form1 class via public Properties to the Form1 class
                    sender.Artist = string.Format("{0}", myMp3.Artist);
                    sender.Album  = string.Format("{0}", myMp3.Album);
                    sender.Genre  = string.Format("{0}", myMp3.Genre);
                    // send all extracted Tags to the Form1 class via 2D array, where it is saved in private fields and where it is send to final DataGrid View
                    sender.TableContr[i] = new string[] { sender.Title, sender.Artist, sender.Album, sender.Genre, sender.Year, sender.FilePaths[i] };
                }
                catch (HundredMilesSoftware.UltraID3Lib.ID3FileException) // Tags are not valid
                {
                    MessageBox.Show("Reading ID3 Tag from file is wrong");
                }
            }
        }
Example #5
0
        public void UltraID3Test()
        {
            UltraID3 ultraID3 = new UltraID3();

            ultraID3.Read(@"e:\Music\Antenne Bayern Radio\Mirror Dawn.mp3");
            testContextInstance.WriteLine(ultraID3.Artist);
            testContextInstance.WriteLine(ultraID3.Genre);

            //ultraID3.Genre = "Rock";
            //ultraID3.Write();

            MPEGFrameInfo mpegFrameInfo = ultraID3.FirstMPEGFrameInfo;

            if (ultraID3.ID3v1Tag.ExistsInFile)
            {
            }
            ID3v2Tag           id3v2Tag = ultraID3.ID3v2Tag;
            ID3FrameCollection frames   = id3v2Tag.Frames;

            for (int i = 0; i < frames.Count; i++)
            {
                ID3v2Frame frame = frames[i];
            }

            id3v2Tag.Genre = "Chillout";
            ultraID3.Write();
        }
Example #6
0
        public void Read(string Filepath)
        {
            u.Read(Filepath);

            this.UserText.Clear();

            foreach (ID3v23UserDefinedTextFrame fr in u.ID3v2Tag.Frames.GetFrames(MultipleInstanceID3v2FrameTypes.ID3v23UserDefinedText))
            {
                this.UserText.Add(fr.Description, fr.UserDefinedText);
            }

            this._Comments = "";
            this._DBInfo   = "";

            foreach (ID3v23CommentsFrame c in u.ID3v2Tag.Frames.GetFrames(MultipleInstanceID3v2FrameTypes.ID3v23Comments))
            {
                // TODO: exclude some other comments such as itune stuff
                if (c.Description != "DBInfo" & !string.IsNullOrEmpty(c.Comments.Trim()))
                {
                    this._Comments += (string.IsNullOrEmpty(this._Comments) ? "" : "\n") + c.Comments;
                }
                else if (c.Description == "DBInfo")
                {
                    this._DBInfo = c.Comments;
                }
            }

            ////u.ID3v2Tag.WillWrite = true;
            ////u.ID3v1Tag.WillWrite = false;
            u.ID3v2Tag.Frames.AddNewFrameTextEncodingType = TextEncodingTypes.Unicode;
        }
Example #7
0
        //<!--
        //<add key="enable.Sorting.Mp3.Artist" value="true" />
        //<add key="enable.Sorting.Mp3.Genre" value="true" />
        //<add key="enable.Sorting.Mp3.Year" value="true" />
        //-->
        public static void Check(string[] args)
        {
            string targetFolder = @"E:\server\index\test\asd-iND";
            string junctionPoint = @"E:\server\index\sortby.Artist";
            Console.WriteLine("targetFolder='{0}'", targetFolder);
            Console.WriteLine("junctionPoint='{0}'", junctionPoint);

            // Create junction point and confirm its properties.
            JunctionPoint.Create(junctionPoint, targetFolder, true /*overwrite*/);
            if (JunctionPoint.Exists(junctionPoint))
            {
                Console.WriteLine("Junction point exists.");
            }
            else
            {
                Console.WriteLine("Junction point doesnt exists.");
            }
            Console.WriteLine(args[0]);
            if (args.Length < 1)
            {
                Console.WriteLine("Give me an Media file as argument!");
            }
            else
            {
                UltraID3 mp3Info = new UltraID3();
                FileInfo fi = new FileInfo(args[0]);
                mp3Info.Read(fi.FullName);
                if (mp3Info.ID3v23Tag.FoundFlag || mp3Info.ID3v1Tag.FoundFlag)
                {
                    Console.WriteLine("Mp3 Info For '{0}':\n{1}", fi.FullName, mp3Info.ToString());
                }
            }
        }
Example #8
0
        /// <summary>
        /// Returns a List of Results for every song in the specified folder.
        /// </summary>
        /// <param name="bgWorker">Used for reporting progress.</param>
        /// <returns></returns>
        public static IEnumerable <Result> CollectTags(System.ComponentModel.BackgroundWorker bgWorker)
        {
            UltraID3       u       = new UltraID3();
            IList <Result> lstTags = new List <Result>();

            string[] files = Directory.GetFiles(musicPath, "*.mp3", SearchOption.AllDirectories);
            var      sw    = new Stopwatch();

            sw.Start();
            foreach (var f in files)
            {
                u.Read(f);
                lstTags.Add(new Result {
                    Artist = u.Artist, Title = u.Title, Album = u.Album, Filename = u.FileName, Genre = u.Genre, Year = u.Year.ToString(), Length = u.Duration.ToString()
                });

                //progress goes from 0 to 100 so we have to normalize
                //also progress needs to be an integer, if not, the progress bar doesn't show anything
                var percentage = (int)(lstTags.Count / (float)files.Length * 100);

                //apart from percentage we send the number of processed files for relating to the user
                bgWorker.ReportProgress(percentage, (new int[] { lstTags.Count, files.Length }));

                Debug.WriteLine(String.Format("Processed {0} of {1}", lstTags.Count, files.Length));
            }
            lstTags.RemoveAt(0);
            sw.Stop();
            Debug.WriteLine(sw.ElapsedMilliseconds / 1000 + " seconds");
            Debug.WriteLine(lstTags.Count);
            return(lstTags);
        }
Example #9
0
 public ID3Helper(string filename)
 {
     id3info = new UltraID3();
     id3info.Read(filename);
     id3info.ID3v1Tag.Clear();
     id3v2tag = id3info.ID3v2Tag;
 }
        Bitmap GetThumbnailFromID3Tag(string fileName)
        {
            UltraID3 myMp3;

            try
            {
                myMp3 = new UltraID3();
                myMp3.Read(fileName);
                ID3FrameCollection myArtworkCollection = myMp3.ID3v2Tag.Frames.GetFrames(MultipleInstanceID3v2FrameTypes.ID3v22Picture);
                Bitmap             tryGetBMP           = getThumbnailFromFrameCollection(myArtworkCollection);

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

                myArtworkCollection = myMp3.ID3v2Tag.Frames.GetFrames(MultipleInstanceID3v2FrameTypes.ID3v23Picture);
                tryGetBMP           = getThumbnailFromFrameCollection(myArtworkCollection);

                return(tryGetBMP);
            }
            catch
            {
                myMp3 = null;
            }

            return(null);
        }
Example #11
0
 private void SaveFiles(IDatabaseProvider dbController, List <string> files)
 {
     foreach (var fi in files)
     {
         try
         {
             var      ii = TagLib.File.Create(fi);
             UltraID3 u  = new UltraID3();
             u.Read(fi);
             MusicItem ti = new MusicItem(ii, u);
             if (!dbController.Match(ti))
             {
                 dbController.AddMusicItem(ti);
                 cnt++;
                 ReportProgressOn();
             }
             else
             {
                 // similar file already exists in db
             }
         }
         catch (Exception ex)
         {
             // throw;
         }
     }
 }
Example #12
0
 public MusicInfo(string file)
 {
     Tags = new UltraID3();
     Tags.Read(file);
     Tags.ID3v1Tag.Clear();
     id3Helper = new ID3Helper(Tags.ID3v2Tag);
 }
Example #13
0
        public void Process(Crawler crawler, PropertyBag propertyBag)
        {
            if (propertyBag.StatusCode != HttpStatusCode.OK)
            {
                return;
            }

            using (TempFile tempFile = new TempFile())
            {
                using (FileStream fs = new FileStream(tempFile.FileName, FileMode.Create, FileAccess.Write, FileShare.Read, 0x1000))
                using (Stream input = propertyBag.GetResponse())
                {
                    input.CopyToStream(fs);
                }

                UltraID3 id3 = new UltraID3();
                id3.Read(tempFile.FileName);

                propertyBag["MP3_Album"].Value = id3.Album;
                propertyBag["MP3_Artist"].Value = id3.Artist;
                propertyBag["MP3_Comments"].Value = id3.Comments;
                propertyBag["MP3_Duration"].Value = id3.Duration;
                propertyBag["MP3_Genre"].Value = id3.Genre;
                propertyBag["MP3_Title"].Value = id3.Title;
            }
        }
Example #14
0
        public static void SetTrackNumber()
        {
            string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;

            foreach (
                string file in
                Directory.EnumerateFiles(exePath.Substring(0, exePath.LastIndexOf("\\") + 1), "*.mp3",
                                         SearchOption.AllDirectories))
            {
                UltraID3 u = new UltraID3();
                u.Read(file);
                string OnlyFileName = u.FileName.Substring(u.FileName.LastIndexOf("\\") + 1).Replace(".mp3", "");

                OnlyFileName = OnlyFileName.Substring(OnlyFileName.Length - 3, 3);

                short trackNumber = Convert.ToInt16(OnlyFileName);

                if (trackNumber <= 255)
                {
                    u.TrackNum = trackNumber;
                    u.Write();
                }
                else
                {
                    WriteLog("Track Length More Than 255 For File Name : " + u.FileName);
                }
            }

            WriteLog("Track Changed");
        }
        private void Load_MusicInfo()
        {
            FileInfo fileInfo = new FileInfo(SMusic);
            UltraID3 myFile   = new UltraID3();

            myFile.Read(fileInfo.FullName);

            Bitmap             musicImgBitmap;
            ID3FrameCollection myFrames = myFile.ID3v2Tag.Frames.GetFrames(MultipleInstanceID3v2FrameTypes.ID3v23Picture);

            try
            {
                musicImgBitmap    = ((ID3v23PictureFrame)myFrames[0]).Picture;
                pictureBox1.Image = musicImgBitmap;
            }
            catch
            {
                pictureBox1.Image = null;
            }

            string fileName = fileInfo.Name;

            double fileSize = fileInfo.Length;

            string duration = Getmp3Duration(SMusic);

            fileFolder       = fileInfo.Directory.FullName;
            lblTitle.Text    = myFile.ID3v2Tag.Title;
            lblArtist.Text   = myFile.ID3v2Tag.Artist;
            lblAlbum.Text    = myFile.ID3v2Tag.Album;
            lblPlayTIme.Text = duration;
            lblMemory.Text   = ((fileSize / 1024) / 1024).ToString("N2") + "MB";
        }
Example #16
0
        private void Load_MusicInfo()
        {
            FileInfo fileInfo = new FileInfo(MusicFile);
            UltraID3 myFile   = new UltraID3();

            myFile.Read(fileInfo.FullName);

            Bitmap             musicImgBitmap;
            ID3FrameCollection myFrames = myFile.ID3v2Tag.Frames.GetFrames(MultipleInstanceID3v2FrameTypes.ID3v23Picture);

            try
            {
                musicImgBitmap = ((ID3v23PictureFrame)myFrames[0]).Picture;
                picAlbum.Image = musicImgBitmap;
            }
            catch
            {
                picAlbum.Image = null;
            }

            string duration = Getmp3Duration(MusicFile);

            lblTitle.Text     = myFile.ID3v2Tag.Title;
            lblArtist.Text    = myFile.ID3v2Tag.Artist;
            lblTotalTime.Text = duration;
        }
        private void DataGridView_MP3s_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                //string path = (string)m_DataGridViewTrackList.Rows[e.RowIndex].Cells[dataGridViewTextBoxColumn10.Name].Value;

                //SelectedTracksPath = path;
                //OnTrackListRowEnter();

                if (m_DataGridViewTrackList.Columns[e.ColumnIndex] == this.dataGridViewImageColumn1)
                {
                    Process mp3PlayerProcess = new Process();

                    mp3PlayerProcess.StartInfo.FileName        = "\"" + SelectedTracksPath + "\"";
                    mp3PlayerProcess.StartInfo.WindowStyle     = ProcessWindowStyle.Minimized;
                    mp3PlayerProcess.StartInfo.UseShellExecute = true;
                    mp3PlayerProcess.Start();
                }
                else if (m_DataGridViewTrackList.Columns[e.ColumnIndex] == this.dataGridViewTextBoxColumn10)
                {
                    UltraID3 uid = new UltraID3();
                    uid.Read(SelectedTracksPath);
                    new MP3TagEditor.Mp3TagEditor(uid).ShowDialog();
                }
            }
            catch { }
        }
        public MusicItem(string filePath)
        {
            var      ii = TagLib.File.Create(filePath);
            UltraID3 u  = new UltraID3();

            u.Read(filePath);
            Init(ii, u);
        }
Example #19
0
        private void ScanDirectoryConcurrent(object searchDirectory)
        {
            int totalFiles = 0;

            try
            {
                DictionaryEntry baseDirectory = (DictionaryEntry)searchDirectory;

                DirectoryInfo di       = new DirectoryInfo(baseDirectory.Key.ToString());
                FileInfo[]    fileList = di.GetFiles("*.mp3",
                                                     (bool)baseDirectory.Value
                                            ? SearchOption.AllDirectories
                                            : SearchOption.TopDirectoryOnly);

                //EnableCancelButton();

                totalFiles = fileList.Length;
                SetProgressMaximum(totalFiles);

                for (int i = 0; i < totalFiles; i++)
                {
                    if (m_CancelScanning)
                    {
                        totalFiles = i;
                        break;
                    }
                    try
                    {
                        UltraID3 id3 = new UltraID3();
                        id3.Read(fileList[i].FullName);

                        m_allTrackList.Add(new Track
                        {
                            Artist   = id3.Artist,
                            Title    = id3.Title,
                            Album    = id3.Album,
                            Genre    = id3.Genre,
                            Length   = id3.Duration,
                            Size     = id3.Size,
                            FileName = fileList[i].Name,
                            Path     = fileList[i].FullName
                        });
                    }
                    catch
                    {
                    }

                    if ((i % 20) == 0)
                    {
                        UpdateProgress(20);
                    }
                }
            }
            finally
            {
                EndRecursiveScanningConcurrent(totalFiles, m_allTrackList);
            }
        }
 public MediaFile(string filePath)
 {
     _lazyFile = new Lazy <UltraID3>(() =>
     {
         var file = new UltraID3();
         file.Read(filePath);
         return(file);
     });
 }
Example #21
0
        public override async void EndOfTrack(SpotifySession session)
        {
            session.PlayerPlay(false);
            wr.Close();

            // Move File
            var dir = downloadPath + escape(downloadingTrack.Album().Name()) + "\\";

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            var fileName = dir + escape(GetTrackFullName(downloadingTrack)) + ".mp3";

            if (GetDownloadType() == DownloadType.OVERWRITE && File.Exists(fileName))
            {
                File.Delete(fileName);
            }
            File.Move("downloading", fileName);

            // Tag
            var u = new UltraID3();

            u.Read(fileName);
            u.Artist   = GetTrackArtistsNames(downloadingTrack);
            u.Title    = downloadingTrack.Name();
            u.Album    = downloadingTrack.Album().Name();
            u.TrackNum = (short)downloadingTrack.Index();
            u.Year     = (short)downloadingTrack.Album().Year();

            var imageID = downloadingTrack.Album().Cover(ImageSize.Large);
            var image   = SpotifySharp.Image.Create(session, imageID);

            await WaitForBool(image.IsLoaded);

            var tc  = TypeDescriptor.GetConverter(typeof(Bitmap));
            var bmp = (Bitmap)tc.ConvertFrom(image.Data());

            var pictureFrame = new ID3v23PictureFrame(bmp, PictureTypes.CoverFront, "image", TextEncodingTypes.ISO88591);

            u.ID3v2Tag.Frames.Add(pictureFrame);

            u.Write();

            base.EndOfTrack(session);

            if (OnDownloadProgress != null)
            {
                OnDownloadProgress(100);
            }

            if (OnDownloadComplete != null)
            {
                OnDownloadComplete(true);
            }
        }
Example #22
0
 public void GetInfo(FileInfo audioFile)
 {
     UltraID3 lib = new UltraID3();
     lib.Read(audioFile.FullName);
     Artist = lib.Artist;
     Album = lib.Album;
     Genre = lib.Genre;
     Bitrate = lib.FirstMPEGFrameInfo.Bitrate.ToString();
     Title = lib.Title;
 }
Example #23
0
        public void GetInfo(FileInfo audioFile)
        {
            UltraID3 lib = new UltraID3();

            lib.Read(audioFile.FullName);
            Artist  = lib.Artist;
            Album   = lib.Album;
            Genre   = lib.Genre;
            Bitrate = lib.FirstMPEGFrameInfo.Bitrate.ToString();
            Title   = lib.Title;
        }
Example #24
0
    public string GetSongInfo(string song, int SID)
    {
        string   toReturn = "\n" + "SID " + SID + "\n";
        UltraID3 id3      = new UltraID3();

        id3.Read(song);
        toReturn += "Title: " + id3.Title + "\n";
        toReturn += "Artist: " + id3.Artist + "\n";
        toReturn += "Album: " + id3.Album;
        return(toReturn);
    }
Example #25
0
 public void RetrieveTagInfo()
 {
     UltraID3 ultraID3 = new UltraID3();
     ultraID3.Read(FileName);
     Title = ultraID3.Title;
     Artist = ultraID3.Artist;
     Album = ultraID3.Album;
     Recorded = ultraID3.Year;
     Comment = ultraID3.Comments;
     Genre = ultraID3.Genre;
     Length = (long)ultraID3.Duration.TotalSeconds;
 }
        private void FillDataGridAsync()
        {
            if (m_DataGridViewTrackList.InvokeRequired)
            {
                this.Invoke(new EmptyMethodCaller(FillDataGridAsync));
                return;
            }

            try
            {
                batchCounting_Artist = new Hashtable();
                batchCounting_Album  = new Hashtable();
                batchCounting_Ganre  = new Hashtable();
                batchCounting_Year   = new Hashtable();

                if (Directory.Exists(m_ActivePath))
                {
                    lock (m_BindingSourceUltraID3.SyncRoot)
                    {
                        m_BindingSourceUltraID3.Clear();

                        foreach (string mp3File in
                                 Directory.GetFiles(
                                     m_ActivePath,
                                     "*.mp3",
                                     SearchOption.AllDirectories))
                        {
                            try
                            {
                                UltraID3 uId3 = new UltraID3();
                                if (uId3.Size == 0)
                                {
                                    continue;
                                }
                                uId3.Read(mp3File);
                                m_BindingSourceUltraID3.Add(uId3);

                                UpdateBestMatch(batchCounting_Album, uId3.Album);
                                UpdateBestMatch(batchCounting_Artist, uId3.Artist);
                                UpdateBestMatch(batchCounting_Ganre, uId3.Genre);
                                UpdateBestMatch(batchCounting_Year, uId3.Year.ToString());
                            }
                            catch { }
                        }

                        this.FillBachFields();
                    }
                }
            }
            catch { }
        }
Example #27
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (Properties.Settings.Default.mode == 1)
            {
                //Setting the progress bar value to 0 and then it sets it t the number of files that end with ".mp3" inside a folder (including subfolders)
                progressBar1.Value = 0;
                progressBar1.Maximum = Directory.GetFiles(Properties.Settings.Default.path, "*.mp3", SearchOption.AllDirectories).Length;

                foreach (string file in Directory.GetFiles(Properties.Settings.Default.path, "*.mp3", SearchOption.AllDirectories))
                {
                    //It uses Ultra ID3 Library to access ID3 tags
                    UltraID3 mp3 = new UltraID3();
                    mp3.Read(file);

                    string title = mp3.Title;

                    //If the title inside ID3 tags isn't empty
                    if (title.Trim() != "")
                    {
                        string[] a1 = file.Split('\\'); //splits the path
                        string final = file.Substring(0, file.Length - a1[a1.Length - 1].Length) + title + ".mp3";
                        if (!File.Exists(final))
                            File.Move(file, final);
                    }

                    progressBar1.Value++;
                }
            }
            if (Properties.Settings.Default.mode == 2)
            {
                //SAME
                progressBar1.Value = 0;
                progressBar1.Maximum = Directory.GetFiles(Properties.Settings.Default.path, "*.mp3", SearchOption.AllDirectories).Length;

                foreach (string file in Directory.GetFiles(Properties.Settings.Default.path, "*.mp3", SearchOption.AllDirectories))
                {
                    UltraID3 mp3 = new UltraID3();
                    mp3.Read(file);

                    string[] a1 = file.Split('\\');
                    string final = a1[a1.Length - 1].Substring(0, a1[a1.Length - 1].Length - 4);

                    mp3.Title = final;

                    mp3.Write();

                    progressBar1.Value++;
                }
            }
        }
Example #28
0
        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex > -1)
            {
                label1.Text = listBox2.Items[listBox1.SelectedIndex].ToString();
                if (Path.GetExtension(label1.Text).Equals(".m4a"))
                {
                    //string tempFile = Path.GetPathRoot(label1.Text) + "test" + Path.GetExtension(label1.Text);
                    //if (File.Exists(tempFile))
                    //File.Delete(tempFile);

                    //File.Move(label1.Text, tempFile);

                    //StreamWriter test = new StreamWriter("read.bat");
                    //test.Write("ap.exe \"" + tempFile + "\" -t -E > read.txt");
                    //test.Close();

                    Process p = new Process();
                    p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    p.StartInfo.FileName    = "ap.exe";
                    p.StartInfo.Arguments   = "\"" + label1.Text + "\"" + " -t -E > read.txt";
                    p.Start();
                    p.WaitForExit();

                    StreamReader streamReader = new StreamReader("read.txt");
                    richTextBox1.Text = streamReader.ReadToEnd();
                    streamReader.Close();


                    //File.Move(tempFile, label1.Text);

                    Analyze();
                }
                else
                {
                    timer2.Start();
                    UltraID3 ID3 = new UltraID3();
                    ID3.Read(label1.Text);
                    infoTitle.Text        = ID3.Title;
                    infoArtist.Text       = ID3.Artist;
                    infoAlbum.Text        = ID3.Album;
                    infoGenre.Text        = ID3.Genre;
                    infoTrackNo.Text      = ID3.TrackNum.ToString();
                    infoTrackNoTotal.Text = ID3.TrackCount.ToString();
                }

                lastSelected = label1.Text;
            }
        }
Example #29
0
        public bool Insert(string file)
        {
            if (connection.State == ConnectionState.Closed)
            {
                connectToDB();
            }

            UltraID3 tagReader = new UltraID3();

            tagReader.Read(file);

            List <Song> sList = Library.getSongs();

            bool Exist = false;

            for (int i = 0; i < sList.Count; i++)
            {
                if (sList[i].File.Replace("\'", "@SQ") == file)
                {
                    Exist = true;
                }
            }

            try
            {
                if (!Exist)
                {
                    string q = "INSERT INTO Songs (filePath, title, artist, album, year, comment, genre) VALUES ('" + file.Replace("\'", "@SQ");
                    q += "', '" + tagReader.Title.ToString().Replace("\'", "@SQ");
                    q += "', '" + tagReader.Artist.ToString().Replace("\'", "@SQ");
                    q += "', '" + tagReader.Album.ToString().Replace("\'", "@SQ");
                    q += "', '" + tagReader.Year.ToString();
                    q += "', '" + tagReader.Comments.ToString().Replace("\'", "@SQ");
                    q += "', '" + tagReader.Genre.ToString() + "');";

                    SqlCommand insertCommand = new SqlCommand(q, connection);
                    insertCommand.ExecuteNonQuery();
                }
            }
            catch
            {
                return(false);
            }

            return(true);
        }
Example #30
0
    static void Main()
    {
        string sourceFile = "D:\\en_windows_8_1_x64_dvd_2707217.iso";
        string destFile   = "E:\\en_windows_8_1_x64_dvd_2707217.iso";

        FileSystem.CopyFile(sourceFile, destFile, UIOption.AllDialogs);

        Console.WriteLine(File.Exists("Computer\\GT-i9300\\Card"));

        UltraID3 mp3TagReader = new UltraID3();

        mp3TagReader.Read(@"This PC\Наско Маринов (GT-I930\Card\Music\01 - W.F.O..mp3");
        Console.WriteLine(mp3TagReader.Title);
        using (StreamWriter sw = File.AppendText("D:\\result.txt"))
        {
            sw.Write(mp3TagReader.Title);
        }
    }
Example #31
0
    public void Read(string url)
    {
        if (File.Exists(url))
        {
            try
            {
                tagReader = new UltraID3();
                tagReader.Read(url);
            }
            catch (IOException ex)
            {
                // unload tagReader
                tagReader = null;

                Debug.WriteLine("Error at ID3Tag class: " + ex.Message);
            }
        }
    }
Example #32
0
 public static IEnumerable<Result> CollectTags()
 {
     UltraID3 u = new UltraID3();
     var lstTags = new List<Result>();
     string[] files = Directory.GetFiles(musicPath, "*.mp3", SearchOption.AllDirectories);
     var sw = new Stopwatch();
     sw.Start();
     foreach (var f in files)
     {
         u.Read(f);
         lstTags.Add(new Result { Artist = u.Artist, Title = u.Title, Album = u.Album, Filename = u.FileName, Genre = u.Genre, Year = u.Year.ToString(), Length = u.Duration.ToString() });
         Debug.WriteLine(lstTags.Count + " items processed");
     }
     lstTags.RemoveAt(0);
     sw.Stop();
     Debug.WriteLine(sw.ElapsedMilliseconds / 1000 + " seconds");
     Debug.WriteLine(lstTags.Count);
     return lstTags;
 }
        private static string destinationFolder = GlobalAppData.Configs.YoutubeDataFolder;// @"E:\Music\Music Helper Youtube Downloads";

        public static MusicItem DownloadAndConvert(string videoUrl)
        {
            var newPath = string.Empty;

            GlobalAppData.SetWait();
            try
            {
                var youtube = YouTube.Default;
                var vid     = youtube.GetVideo(videoUrl);
                newPath = Path.Combine(destinationFolder, vid.FullName);
                File.WriteAllBytes(newPath, vid.GetBytes());

                var inputFile = new MediaFile {
                    Filename = newPath
                };
                var outputFile = new MediaFile {
                    Filename = $"{newPath}.mp3"
                };

                using (var engine = new Engine())
                {
                    engine.GetMetadata(inputFile);
                    engine.Convert(inputFile, outputFile);
                    newPath = $"{newPath}.mp3";
                }
                File.Delete(inputFile.Filename);
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                GlobalAppData.EndWait();
            }
            var      ii = TagLib.File.Create(newPath);
            UltraID3 u  = new UltraID3();

            u.Read(newPath);
            MusicItem ti = new MusicItem(ii, u);

            return(ti);
        }
Example #34
0
        private void AddTrack(FileInfo file)
        {
            try
            {
                var ultraId3 = new UltraID3();
                ultraId3.Read(file.FullName);

                var track = new TrackModel()
                                {
                                    Id = Guid.NewGuid(),
                                    Name = ultraId3.Title,
                                    Genre = ultraId3.Genre,
                                    Duration = ultraId3.Duration.TotalSeconds,
                                    Number = ultraId3.TrackNum,
                                    Path = file.FullName,
                                    Year = ultraId3.Year
                                };

                var album = GetAlbum(ultraId3.Artist, ultraId3.Album);

                var id3PictureFrames = ultraId3.ID3v2Tag.Frames.GetFrames(MultipleInstanceID3v2FrameTypes.ID3v23Picture);
                if (id3PictureFrames != null && id3PictureFrames.Count > 0)
                {
                    track.Image = string.Format(@"{0}\\Images\\{1}.png", Path, album.Id);

                    if (!System.IO.File.Exists(track.Image))
                        (((ID3v23PictureFrame) id3PictureFrames[0]).Picture).Save(track.Image,
                                                                              System.Drawing.Imaging.ImageFormat.Png);
                }

                album.Year = ultraId3.Year;
                album.Genre = ultraId3.Genre;
                album.Image = track.Image;
                album.Tracks.Add(track);
            }
            catch (Exception ex)
            {
                // Log : File failed to be added
                //throw new Exception(string.Format("File failed to be added {0}", file.FullName), ex);
            }
        }
Example #35
0
        public void Process(Crawler crawler, PropertyBag propertyBag)
        {
            if (propertyBag.StatusCode != HttpStatusCode.OK)
            {
                return;
            }

            using (TempFile tempFile = new TempFile())
            {
                File.WriteAllBytes(tempFile.FileName, propertyBag.Response);
                UltraID3 id3 = new UltraID3();
                id3.Read(tempFile.FileName);

                propertyBag["MP3_Album"].Value = id3.Album;
                propertyBag["MP3_Artist"].Value = id3.Artist;
                propertyBag["MP3_Comments"].Value = id3.Comments;
                propertyBag["MP3_Duration"].Value = id3.Duration;
                propertyBag["MP3_Genre"].Value = id3.Genre;
                propertyBag["MP3_Title"].Value = id3.Title;
            }
        }
Example #36
0
        public void Process(Crawler crawler, PropertyBag propertyBag)
        {
            if (propertyBag.StatusCode != HttpStatusCode.OK)
            {
                return;
            }

            using (TempFile tempFile = new TempFile())
            {
                File.WriteAllBytes(tempFile.FileName, propertyBag.Response);
                UltraID3 id3 = new UltraID3();
                id3.Read(tempFile.FileName);

                propertyBag["MP3_Album"].Value    = id3.Album;
                propertyBag["MP3_Artist"].Value   = id3.Artist;
                propertyBag["MP3_Comments"].Value = id3.Comments;
                propertyBag["MP3_Duration"].Value = id3.Duration;
                propertyBag["MP3_Genre"].Value    = id3.Genre;
                propertyBag["MP3_Title"].Value    = id3.Title;
            }
        }
Example #37
0
        public static void CompareFileNameWithTitle()
        {
            string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;

            int maxFileName = 0;

            foreach (string file in Directory.EnumerateFiles(exePath.Substring(0, exePath.LastIndexOf("\\") + 1), "*.mp3", SearchOption.AllDirectories))
            {
                UltraID3 u = new UltraID3();
                u.Read(file);
                string OnlyFileName = u.FileName.Substring(u.FileName.LastIndexOf("\\") + 1).Replace(".mp3", "");

                maxFileName = maxFileName < OnlyFileName.Length ? OnlyFileName.Length : maxFileName;

                WriteLog(string.Format("{0}\t{1}", OnlyFileName, u.Title));
            }

            WriteLog(maxFileName.ToString());

            WriteLog("Comparation Done");
        }
Example #38
0
        public static void ChangeAlbumWithParentFolder()
        {
            string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;

            int fileCount = 0;

            foreach (string file in Directory.EnumerateFiles(exePath.Substring(0, exePath.LastIndexOf("\\") + 1), "*.mp3", SearchOption.AllDirectories))
            {
                UltraID3 u = new UltraID3();
                u.Read(file);

                string ParentFolderName =
                    u.FileName.Substring(u.FileName.LastIndexOf("\\", u.FileName.LastIndexOf("\\") - 1) + 1,
                                         u.FileName.LastIndexOf("\\", u.FileName.LastIndexOf("\\")) -
                                         u.FileName.LastIndexOf("\\", u.FileName.LastIndexOf("\\") - 1) - 1);

                try
                {
                    if (ParentFolderName.Length >= 30)
                    {
                        WriteLog("Length More Than 30 For Album Name : " + ParentFolderName);
                        u.Album = ParentFolderName.Substring(0, 30);
                    }
                    else
                    {
                        u.Album = ParentFolderName;
                    }

                    u.Write();
                    WriteLog("Done For File Name : " + u.FileName);

                    fileCount++;
                }
                catch (Exception e)
                {
                    WriteLog("Following Error For File : " + u.FileName);
                    WriteLog(e.Message);
                }
            }
        }
Example #39
0
        public int TratarInfo(string caminho)
        {
            int processed = 0;

            string[] lstArquivos = Directory.GetFiles(caminho, "*.mp3");

            bool achou;

            foreach (string arq in lstArquivos)
            {
                achou = false;
                u.Read(arq);
                if (string.IsNullOrEmpty(u.Title))
                {
                    achou   = true;
                    u.Title = BuscarDados(arq);
                }

                if (string.IsNullOrEmpty(u.Artist))
                {
                    achou    = true;
                    u.Artist = BuscarDados(arq, true);
                }

                if (string.IsNullOrEmpty(u.Album))
                {
                    achou   = true;
                    u.Album = "[Baixados]";
                }

                if (achou)
                {
                    u.Write();
                    processed++;
                }
            }

            return(processed);
        }
Example #40
0
        public static void ChangeTitleWithFileName()
        {
            string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;

            int fileCount = 0;

            foreach (string file in Directory.EnumerateFiles(exePath.Substring(0, exePath.LastIndexOf("\\") + 1), "*.mp3", SearchOption.AllDirectories))
            {
                UltraID3 u = new UltraID3();
                u.Read(file);
                string OnlyFileName = u.FileName.Substring(u.FileName.LastIndexOf("\\") + 1).Replace(".mp3", "");
                try
                {
                    if (OnlyFileName.Length >= 30)
                    {
                        WriteLog("Length More Than 30 For File Name : " + u.FileName);
                        u.Title = OnlyFileName.Substring(0, 30);
                    }
                    else
                    {
                        u.Title = OnlyFileName;
                    }

                    u.Write();
                    WriteLog("Done For File Name : " + u.FileName);

                    fileCount++;
                }
                catch (Exception e)
                {
                    WriteLog("Following Error For File : " + u.FileName);
                    WriteLog(e.Message);
                }
            }
            Console.WriteLine("All Done For File Number : " + fileCount);
        }
        private void DataGridView_MP3s_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                //string path = (string)m_DataGridViewTrackList.Rows[e.RowIndex].Cells[dataGridViewTextBoxColumn10.Name].Value;

                //SelectedTracksPath = path;
                //OnTrackListRowEnter();

                if (m_DataGridViewTrackList.Columns[e.ColumnIndex] == this.dataGridViewImageColumn1)
                {

                    Process mp3PlayerProcess = new Process();

                    mp3PlayerProcess.StartInfo.FileName = "\"" + SelectedTracksPath + "\"";
                    mp3PlayerProcess.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
                    mp3PlayerProcess.StartInfo.UseShellExecute = true;
                    mp3PlayerProcess.Start();

                }
                else if (m_DataGridViewTrackList.Columns[e.ColumnIndex] == this.dataGridViewTextBoxColumn10)
                {
                    UltraID3 uid = new UltraID3();
                    uid.Read(SelectedTracksPath);
                    new MP3TagEditor.Mp3TagEditor(uid).ShowDialog();
                }
            }
            catch { }
        }
        private void FillDataGridAsync()
        {
            if (m_DataGridViewTrackList.InvokeRequired)
            {
                this.Invoke(new EmptyMethodCaller(FillDataGridAsync));
                return;
            }

            try
            {
                batchCounting_Artist = new Hashtable();
                batchCounting_Album = new Hashtable();
                batchCounting_Ganre = new Hashtable();
                batchCounting_Year = new Hashtable();

                if (Directory.Exists(m_ActivePath))
                {
                    lock (m_BindingSourceUltraID3.SyncRoot)
                    {

                        m_BindingSourceUltraID3.Clear();

                        foreach (string mp3File in
                                Directory.GetFiles(
                                   m_ActivePath,
                                    "*.mp3",
                                    SearchOption.AllDirectories))
                        {
                            try
                            {
                                UltraID3 uId3 = new UltraID3();
                                if (uId3.Size == 0) continue;
                                uId3.Read(mp3File);
                                m_BindingSourceUltraID3.Add(uId3);

                                UpdateBestMatch(batchCounting_Album, uId3.Album);
                                UpdateBestMatch(batchCounting_Artist, uId3.Artist);
                                UpdateBestMatch(batchCounting_Ganre, uId3.Genre);
                                UpdateBestMatch(batchCounting_Year, uId3.Year.ToString());

                            }
                            catch { }
                        }

                        this.FillBachFields();
                    }
                }
            }
            catch { }
        }
        // Update ID3 tags on the downloaded mp3
        private void tagFile(MusicFile file)
        {
            int iRetries = 0;
            _files[0].DownloadedFile.Refresh();
            while ((!_files[0].DownloadedFile.Exists || _files[0].DownloadedFile.Length == 0) && iRetries < 30)
            {
                // Downloaded, but not flushed?  Sleep for a little while.
                iRetries++;
                System.Threading.Thread.Sleep(1000);
                _files[0].DownloadedFile.Refresh();
            }

            if (iRetries == 30)
            {
                // The file was never written.  We really need some proper error handling, but this will have to
                // do for now.
                throw new Exception("File " + _files[0].DownloadedFile.Name + " has a size of zero bytes and cannot be tagged.");
            }
            else
            {
                UltraID3 tagger = new UltraID3();
                tagger.Read(file.DownloadedFile.FullName);

                tagger.ID3v2Tag.Album = file.Album;
                tagger.ID3v2Tag.Artist = file.Artist;
                tagger.ID3v2Tag.Title = file.Title;

                tagger.Write();
            }
        }
        Bitmap GetThumbnailFromID3Tag(string fileName)
        {
            UltraID3 myMp3;
            try
            {
                myMp3 = new UltraID3();
                myMp3.Read(fileName);
                ID3FrameCollection myArtworkCollection = myMp3.ID3v2Tag.Frames.GetFrames(MultipleInstanceID3v2FrameTypes.ID3v22Picture);
                Bitmap tryGetBMP = getThumbnailFromFrameCollection(myArtworkCollection);

                if (tryGetBMP != null) return tryGetBMP;

                myArtworkCollection = myMp3.ID3v2Tag.Frames.GetFrames(MultipleInstanceID3v2FrameTypes.ID3v23Picture);
                tryGetBMP = getThumbnailFromFrameCollection(myArtworkCollection);

                return tryGetBMP;
            }
            catch
            {
                myMp3 = null;
            }

            return null;
        }
Example #45
0
 public string GetSongInfo(string song, int SID)
 {
     string toReturn = "\n" + "SID " + SID + "\n";
     UltraID3 id3 = new UltraID3();
     id3.Read(song);
     toReturn += "Title: " + id3.Title + "\n" ;
     toReturn += "Artist: " + id3.Artist + "\n";
     toReturn += "Album: " + id3.Album;
     return toReturn;
 }
        private void FillDataGrid()
        {
            try
            {
                my_dataTable_ID3Info.Clear();
                my_dataTable_FileInfo.Clear();

                foreach( string _dir in this.my_checkedListBox_FolderList.CheckedItems )
                {
                    if( System.IO.Directory.Exists( _dir ) )
                    {
                        SearchOption _so =
                            ( toolStripButtonIncluedeSubdirectories.Checked)
                            ? SearchOption.AllDirectories
                            : SearchOption.TopDirectoryOnly;

                        foreach( string mp3file in
                                Directory.GetFiles(
                                   _dir,
                                    "*.mp3",
                                    _so ) )
                        {
                            try
                            {
                                UltraID3 uID3 = new UltraID3();
                                uID3.Read( mp3file );
                                if( !this.FileExistsInFileInfoDS( uID3 ) )
                                {
                                    DataRow _dr = my_dataTable_FileInfo.NewRow();
                                    _dr[my_fileinfo_dc_name] = uID3.Title;
                                    _dr[my_fileinfo_dc_size] = uID3.Size;
                                    _dr[my_fileinfo_dc_duration] = uID3.Duration;

                                    my_dataTable_FileInfo.Rows.Add( _dr );
                                }

                                try
                                {
                                    int? _d_id;

                                    if( ! this.FileExistsInID3InfoDS( uID3 ) &&
                                        ( _d_id = this.GetDuplicateId( uID3 ) ) != null
                                        )
                                    {
                                        DataRow _dr_mp3duplicate = my_dataTable_ID3Info.NewRow();
                                        _dr_mp3duplicate[my_id3Info_dc_artist] = uID3.Artist;
                                        _dr_mp3duplicate[my_id3Info_dc_delete] = false;
                                        _dr_mp3duplicate[my_id3Info_dc_dupl_id] = _d_id; // _dr[my_fileinfo_dc_id];
                                        _dr_mp3duplicate[my_id3Info_dc_duration] = uID3.Duration;
                                        _dr_mp3duplicate[my_id3Info_dc_path] = uID3.FileName;
                                        _dr_mp3duplicate[my_id3Info_dc_size] = uID3.Size;
                                        _dr_mp3duplicate[my_id3Info_dc_title] = uID3.Title;

                                        my_dataTable_ID3Info.Rows.Add( _dr_mp3duplicate );
                                    }
                                } catch { }

                            } catch { }
                        }

                    }
                }

                for( int a = my_dataTable_FileInfo.Rows.Count-1; a > -1 ; a-- )
                {
                    DataRow _dr = my_dataTable_FileInfo.Rows[a];
                    int i = (int)my_dataTable_ID3Info.Compute( "COUNT(" + my_id3Info_dc_dupl_id.ColumnName + ")", my_id3Info_dc_dupl_id.ColumnName + " = " + _dr[my_fileinfo_dc_id].ToString() );
                    if(i < 2){
                        my_dataTable_FileInfo.Rows[a].Delete();
                    }
                }
                my_dataTable_FileInfo.AcceptChanges();
                my_dataTable_ID3Info.AcceptChanges();
            } catch { }
            my_dataGridView.DataSource = my_dataSet;
            my_dataGridView.DataMember = my_dataTable_FileInfo.TableName;
            my_dataGridView.Refresh();
        }
Example #47
0
        /// <summary>
        /// Removes all image frames from the parameter mp3.
        /// Returns true if any files were removed.
        /// </summary>
        private static bool RemoveAllImages(string p_musicPath)
        {
            bool removed = false;

            UltraID3 myMp3 = new UltraID3();
            myMp3.Read(p_musicPath);

            // frame collection consists of all ID3v2 data, in addition to images
            // therefore, must only delete image frames
            // start by getting only the image frames

            ID3FrameCollection imageFrames =
                myMp3.ID3v23Tag.Frames.GetFrames(MultipleInstanceFrameTypes.Picture);

            if (imageFrames.Count > 0)
            {
                myMp3.ID3v23Tag.Frames.Remove(FrameTypes.Picture);

                myMp3.ID3v23Tag.WriteFlag = true;
                myMp3.Write();

                removed = true;
            }

            // clean up local variables

            imageFrames.Clear();
            myMp3 = null;

            return removed;
        }
        private void ScanDirectoryConcurrent(object searchDirectory)
        {
            int totalFiles = 0;

              try
              {
            DictionaryEntry baseDirectory = (DictionaryEntry) searchDirectory;

            DirectoryInfo di = new DirectoryInfo(baseDirectory.Key.ToString());
            FileInfo[] fileList = di.GetFiles("*.mp3",
                                          (bool) baseDirectory.Value
                                            ? SearchOption.AllDirectories
                                            : SearchOption.TopDirectoryOnly);

            //EnableCancelButton();

            totalFiles = fileList.Length;
            SetProgressMaximum(totalFiles);

            for (int i = 0; i < totalFiles; i++)
            {
              if (m_CancelScanning)
              {
            totalFiles = i;
            break;
              }
              try
              {
            UltraID3 id3 = new UltraID3();
            id3.Read(fileList[i].FullName);

            m_allTrackList.Add(new Track
                                 {
                                   Artist = id3.Artist,
                                   Title = id3.Title,
                                   Album = id3.Album,
                                   Genre = id3.Genre,
                                   Length = id3.Duration,
                                   Size = id3.Size,
                                   FileName = fileList[i].Name,
                                   Path = fileList[i].FullName
                                 });
              }
              catch
              {
              }

              if ((i%20) == 0)
              {
            UpdateProgress(20);
              }
            }
              }
              finally
              {
            EndRecursiveScanningConcurrent(totalFiles, m_allTrackList);
              }
        }
        public void DetectUnrecordedMP3S()
        {
            List<string> newMP3s = new List<string>();
            string[] files = Directory.GetFiles(MusicDirectory, "*" + EXTENSION_MP3);
            foreach (string f in files)
                if (!mTracks.Contains(Path.GetFileName(f)))
                    newMP3s.Add(f);

            if (newMP3s.Count == 0)
                return;

            if (MessageBox.Show(String.Format(MESSAGE_UNRECORDED_MP3S, newMP3s.Count),
                "Unrecorded MP3s", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) {
                foreach (string f in newMP3s) {
                    Track tune = new Track();
                    tune.Filename = Path.GetFileName(f);
                    tune.Title = Path.GetFileNameWithoutExtension(f);
                    tune.IsTheme = true;

                    // Get ID3 tags
                    UltraID3 ID3 = new UltraID3();
                    ID3.Read(f);
                    tune.Song = ID3.Title;
                    tune.TrackLength = (int)ID3.Duration.TotalSeconds;
                    mTracks.Add(tune);
                }
            }
        }
Example #50
0
        public override async void EndOfTrack(SpotifySession session)
        {
            session.PlayerPlay(false);
            wr.Close();

            // Move File
            string album = downloadingTrack.Album().Name();
            album = filterForFileName(album);

            var dir = downloadPath + album + "\\";
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            string song = GetTrackFullName(downloadingTrack);
            song = filterForFileName(song);

            var fileName = dir + song + ".mp3";

            try
            {
                File.Move("downloading", fileName);
                FileInfo fileInfo = new FileInfo(fileName);
                String path = fileInfo.DirectoryName;
            }
            catch (Exception e) {

                File.Delete("downloading");
                LogString("Track deleted because the track already exists! Path: " + fileName + " Track Name:" + SpotifyDownloader.GetTrackFullName(downloadingTrack));
                
                base.EndOfTrack(session);

                if (OnDownloadProgress != null)
                    OnDownloadProgress(100);

                if (OnDownloadComplete != null)
                    OnDownloadComplete();
                
                return;
            }

            try
            {
                // Tag
                var u = new UltraID3();
                //u.GetMPEGTrackInfo();
                u.Read(fileName);
                u.Artist = GetTrackArtistsNames(downloadingTrack);
                u.Title = downloadingTrack.Name();
                u.Album = downloadingTrack.Album().Name();

                var imageID = downloadingTrack.Album().Cover(ImageSize.Large);
                var image = SpotifySharp.Image.Create(session, imageID);
                await WaitForBool(image.IsLoaded);

                var tc = TypeDescriptor.GetConverter(typeof(Bitmap));
                var bmp = (Bitmap)tc.ConvertFrom(image.Data());

                var pictureFrame = new ID3v23PictureFrame(bmp, PictureTypes.CoverFront, "image", TextEncodingTypes.ISO88591);
                u.ID3v2Tag.Frames.Add(pictureFrame);

                u.Write();

                base.EndOfTrack(session);
            }
            catch (Exception e) { };

            LogString("Track downloaded and saved! Path: " + fileName + " Track Name:" + SpotifyDownloader.GetTrackFullName(downloadingTrack));

            if (OnDownloadProgress != null)
                OnDownloadProgress(100);

            if (OnDownloadComplete != null)
                OnDownloadComplete();
        }
Example #51
0
        /// <summary>
        /// Attaches the cover file to the mp3's picture frames.
        /// </summary>
        private static void AttachCover(string p_musicPath, string p_coverPath)
        {
            UltraID3 myMp3 = new UltraID3();
            myMp3.Read(p_musicPath);

            System.Drawing.Bitmap cover = new System.Drawing.Bitmap(p_coverPath);
               // cover = new System.Drawing.Bitmap(cover.GetThumbnailImage(100, 100, null, IntPtr.Zero));

            ID3PictureFrame AlbumArt = new ID3PictureFrame(
                cover, PictureTypes.CoverFront, "Attached picture", TextEncodingTypes.ISO88591);

            myMp3.ID3v23Tag.Frames.Add(AlbumArt);
            myMp3.ID3v23Tag.WriteFlag = true;
            myMp3.Write();

            myMp3 = null;
        }
 private void SetID3Tags(Track track, string path)
 {
     try
     {
         var tagger = new UltraID3();
         tagger.Read(path);
         tagger.Title = track.Title;
         tagger.Artist = track.User.Username;
         tagger.Genre = track.Genre;
         tagger.Write();
     }
     catch (Exception ex)
     {
         LogSpecial("Error tagging ", string.Empty, ".", track.Title, string.Empty);
         Log(ex.Message);
     }
 }
Example #53
0
        /* inserts new track to XML file */
        public void InsertTrack(string TargetPath, string FileType)
        {
            TagLib.File tag;
            UltraID3 uTag;
            XElement Track;
            string title;
            string album;
            string artist;
            string trackNum;
            int num;
            string year;

            // check for nulls on these and fill in dummy values (Unknown Artist)
            tag = TagLib.File.Create(TargetPath);
            uTag = new UltraID3();
            uTag.Read(TargetPath);

            if ((artist = tag.Tag.FirstAlbumArtist) == null)
                if ((artist = tag.Tag.FirstPerformer) == null)
                    if(((artist = uTag.Artist) == "") || (artist == null))
                        artist = "Unknown Artist";

            if ((title = tag.Tag.Title) == null)
                if(((title = uTag.Title) == "" ) || (title == null))
                    title = Path.GetFileNameWithoutExtension(TargetPath);

            if ((album = tag.Tag.Album) == null)
                if(((album = uTag.Album) == "") || (album == null))
                    album = "Unknown Album";

            if (((year = tag.Tag.Year.ToString()) == null) || (year == "0"))
                if (((year = uTag.Year.ToString()) == "") || (year == null))
                    year = "0";

            if ((trackNum = tag.Tag.Track.ToString()) == null || (trackNum == "0"))
                if (((trackNum = uTag.TrackNum.ToString()) == "") || (trackNum == null))
                    trackNum = "0";

            if (trackNum.Length == 1)
            {
                trackNum = "0" + trackNum;
            }

            // get library track counter and increment
            root.Attribute("Count").SetValue((num = Int32.Parse(root.Attribute("Count").Value) + 1).ToString());

            // create track element and insert to xml tree
            Track =
                new XElement("Track",
                    new XAttribute("ID", num),
                    new XElement("TrackNumber", trackNum),
                    new XElement("Title", title),
                    new XElement("Album", album),
                    new XElement("Artist", artist),
                    new XElement("Year", year),
                    new XElement("DateAdded", DateTime.Now.ToString("g")),
                    new XElement("Path", TargetPath),
                    new XElement("Type", FileType)
                );
            root.Add(Track);
        }
Example #54
0
 public bool Download()
 {
     bool success = false;
     UltraID3 u = new UltraID3();
     if (!Directory.Exists(_LocalDir))
         Directory.CreateDirectory(_LocalDir);
     if (!File.Exists(_LocalUrl))
     {
         try { wc.DownloadFile(_RemoteUrl, _LocalUrl); success = true; }
         catch { Console.ForegroundColor = ConsoleColor.Red; }
     }
     else
         success = true;
     u.Read(_LocalUrl);
     u.ID3v2Tag.Album = _Album;
     u.ID3v2Tag.Artist = _Artist;
     u.ID3v2Tag.Title = _Title;
     u.ID3v2Tag.TrackNum = _TrackNum;
     AddAlbumArt(Path.Combine(_LocalDir, albumArtFilename), u);
     u.Write();
     return success;
 }
Example #55
0
        public bool Insert(string file)
        {
            if (connection.State == ConnectionState.Closed)
            {
                connectToDB();
            }

            UltraID3 tagReader = new UltraID3();
            tagReader.Read(file);

            List<Song> sList = Library.getSongs();

            bool Exist = false;

            for (int i = 0; i < sList.Count; i++ )
            {
                if (sList[i].File.Replace("\'", "@SQ") == file)
                    Exist = true;
            }

            try
            {

                if (!Exist)
                {
                    string q = "INSERT INTO Songs (filePath, title, artist, album, year, comment, genre) VALUES ('" + file.Replace("\'", "@SQ");
                    q += "', '" + tagReader.Title.ToString().Replace("\'", "@SQ");
                    q += "', '" + tagReader.Artist.ToString().Replace("\'", "@SQ");
                    q += "', '" + tagReader.Album.ToString().Replace("\'", "@SQ");
                    q += "', '" + tagReader.Year.ToString();
                    q += "', '" + tagReader.Comments.ToString().Replace("\'", "@SQ");
                    q += "', '" + tagReader.Genre.ToString() + "');";

                    SqlCommand insertCommand = new SqlCommand(q, connection);
                    insertCommand.ExecuteNonQuery();
                }
            }
            catch
            {
                return false;
            }

            return true;

        }
    private void RenderPlaylistTracks(List<FileInfo> mediaFiles, PlaylistType playlist, bool shuffle)
    {
        List<TrackType> trackList = new List<TrackType>();

        string songPathPrefix = string.Format("{0}/Handlers/Song.ashx?",
                                    this.Request.ApplicationPath.TrimEnd('/'));
        string imagePathPrefix = string.Format("{0}/Handlers/CoverArt.ashx?",
                                    this.Request.ApplicationPath.TrimEnd('/'));

        foreach (FileInfo mediaFileInfo in mediaFiles)
        {
            if (!mediaFileInfo.Exists)
                continue;

            TrackType trackInfo = new TrackType();

            try
            {
                UltraID3 mp3Info = new UltraID3();
                mp3Info.Read(mediaFileInfo.FullName);

                if (!mp3Info.ID3v23Tag.FoundFlag && !mp3Info.ID3v23Tag.FoundFlag)
                {
                    // No tags
                    trackInfo.title = mediaFileInfo.Name.Substring(0, mediaFileInfo.Name.Length - mediaFileInfo.Extension.Length);
                }
                else
                {
                    // Image
                    if (mp3Info.ID3v23Tag.FoundFlag)
                    {
                        ID3FrameCollection pictureFrames = mp3Info.ID3v23Tag.Frames.GetFrames(MultipleInstanceFrameTypes.Picture);
                        if(pictureFrames.Count > 0) // File has picture
                            trackInfo.image = imagePathPrefix + HttpContext.Current.Server.UrlEncode(mediaFileInfo.FullName);
                    }

                    // Title
                    if (mp3Info.Title == null || mp3Info.Title.Length == 0)
                        trackInfo.title = mediaFileInfo.Name.Substring(0, mediaFileInfo.Name.Length - mediaFileInfo.Extension.Length - 1);
                    else
                        trackInfo.title = mp3Info.Title;

                    trackInfo.album = mp3Info.Album;
                    trackInfo.creator = mp3Info.Artist;
                    trackInfo.annotation = mp3Info.Comments;
                    if (mp3Info.TrackNum.HasValue)
                        trackInfo.trackNum = mp3Info.TrackNum.Value.ToString();
                }
            }
            catch
            {
                trackInfo.title = mediaFileInfo.Name.Substring(0, mediaFileInfo.Name.Length - mediaFileInfo.Extension.Length);
            }

            trackInfo.location = new string[1];
            trackInfo.location[0] = songPathPrefix + HttpContext.Current.Server.UrlEncode(mediaFileInfo.FullName);

            if (trackInfo.title != null && trackInfo.title.Length > 0)
                trackList.Add(trackInfo);

            if (trackInfo.image == null || trackInfo.image.Length == 0)
                trackInfo.image = string.Format("{0}/Images/NoCoverArt.jpg", this.Request.ApplicationPath.TrimEnd('/'));

            //System.GC.Collect();
        }

        playlist.trackList = trackList.ToArray();

        if (shuffle)
            UtilityMethods.ShuffleArray(playlist.trackList);
    }
Example #57
0
        private void btnDownload_Click(object sender, EventArgs e)
        {
            string finalPath;
            SetEnabled(false);
            SetInfo("Downloading Songs");
            totalTracksCount = m_lbxEntries.CheckedItems.Count;
            var tracks = m_lbxEntries.CheckedItems.Cast<Track>();

            if (chkBxDownloadPath.Checked)
            {
                finalPath = downloadFolder;
            }
            else
            {
                finalPath = m_Direcotry;
            }

            if (type != SearchType.TRACK)
            {
                finalPath = Path.Combine(finalPath, title);
                if (!System.IO.Directory.Exists(finalPath))
                {
                    System.IO.Directory.CreateDirectory(finalPath);
                }
            }

            ThreadPool.QueueUserWorkItem(
                (_) =>
                {
                    foreach (var track in tracks)
                    {
                        string fileName = String.Format("{0}.mp3", track.title);
                        foreach (var chr in Path.GetInvalidFileNameChars().Union(Path.GetInvalidPathChars()))
                        {
                            fileName = fileName.Replace("" + chr, "_");
                        }

                        SetInfo("Downloading " + fileName);
                        tracksCount++;

                        tempDownloadFolder = Path.Combine(finalPath, fileName);

                        if (File.Exists(tempDownloadFolder))
                        {
                            if (chkBxSkip.Checked)
                            {
                                continue;
                            }
                            else
                            {
                                File.Delete(tempDownloadFolder);
                            }
                        }

                        string url = String.Format("{0}/stream.json?client_id={1}", track.uri, clientID);
                        wbClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                        wbClient.DownloadFileCompleted += HandleDownloadComplete;

                        var syncObject = new Object();
                        lock (syncObject)
                        {
                            wbClient.DownloadFileAsync(new Uri(url), tempDownloadFolder, syncObject);
                            Monitor.Wait(syncObject);
                        }

                        var u = new UltraID3();
                        u.Read(tempDownloadFolder);
                       
                        if (track.artwork_url != null && chkBxImageTags.Checked)
                        {
                            Stream stream = wbClient.OpenRead(track.artwork_url);
                            Bitmap bmp = new Bitmap(stream);

                            var pictureFrame = new ID3v23PictureFrame(bmp, PictureTypes.CoverFront, "image", TextEncodingTypes.ISO88591);
                            u.ID3v2Tag.Frames.Add(pictureFrame);
                        }
                        if (track.title.Contains("-"))
                        {
                            string[] splitTitle = track.title.Split('-');
                            u.Title = splitTitle[1];
                            if (chkBxArtistTag.Checked)
                            {
                                u.Artist = splitTitle[0]; //((User)track.user).username;
                            }
                        }
                        else
                        {
                            u.Title = track.title;
                        }
                        u.Write();
                    }

                    SetInfo("Finished Downloading!");
                    SetEnabled(true);
                    SetChecked(false);
                    totalTracksCount = 0;
                    tracksCount = 0;
                    if (chkBxOpenFolder.Checked)
                    {
                        System.Diagnostics.Process.Start("explorer.exe", finalPath);
                    }
                });
        }
Example #58
0
 public static int GetInfos(string dirName, int depth)
 {
     mLog.InfoFormat("dirName='{0}', depth={1}", dirName, depth);
     if (Directory.Exists(dirName))
     {
         DirectoryInfo di = new DirectoryInfo(dirName);
         DirectoryInfo[] diArr = di.GetDirectories();
         if (diArr.Length > 0)
         {
             if (depth > 1)
             {
                 foreach (DirectoryInfo dri in diArr)
                 {
                     GetInfos(dri.FullName, depth - 1);
                 }
             }
             else
             {
                 //get mp3 infos
                 foreach (DirectoryInfo dri in diArr)
                 {
                     mLog.DebugFormat("Checking '{0}'", dri.FullName);
                     FileInfo[] rgFiles = dri.GetFiles("*.mp3");
                     int filesCount = rgFiles.Length;
                     if (filesCount > 0)
                     {
                         mLog.DebugFormat("Found {0} Mp3 Files In '{1}'", filesCount, dri.FullName);
                         Console.WriteLine("-{0}", dri.FullName);
                         bool found = false;
                         foreach (FileInfo file in rgFiles)
                         {
                             if (found)
                             {
                                 break;
                             }
                             mLog.DebugFormat("Get Mp3 Info For '{0}'", file.FullName);
                             UltraID3 mp3Info = new UltraID3();
                             mp3Info.Read(file.FullName);
                             if (mp3Info.ID3v23Tag.FoundFlag || mp3Info.ID3v1Tag.FoundFlag)
                             {
                                 mLog.DebugFormat("Mp3 Info For '{0}':\n{1}", file.FullName, mp3Info.ToString());
                                 found = true;
                                 CreateSymlinks(dri.FullName, dri.Name, "Artist", mp3Info.Artist);
                                 CreateSymlinks(dri.FullName, dri.Name, "Year", mp3Info.Year.ToString());
                                 CreateSymlinks(dri.FullName, dri.Name, "Genre", mp3Info.Genre);
                             }
                         }
                     }
                     else
                     {
                         mLog.InfoFormat("Directory '{0}' Doesnt Have Any Mp3 Files!", dri.FullName);
                     }
                 }
             }
         }
         else
         {
             mLog.WarnFormat("'{0}' Has No Directories!", dirName);
         }
     }
     else
     {
         mLog.WarnFormat("'{0}' Doesnt Exists!", dirName);
     }
     return 0;
 }
Example #59
0
        /// <summary>
        /// 
        /// </summary>
        private static void AttachIDv2(string p_musicPath)
        {
            UltraID3 myMp3 = new UltraID3();
            myMp3.Read(p_musicPath);

            // get base data

            string band = myMp3.Artist;
            string album = myMp3.Album;
            string title = myMp3.Title;
            string genre = myMp3.Genre;
            short? year = myMp3.Year;

            // create IDv2 frames if necessary

            if (myMp3.ID3v23Tag.Frames.Count <= 1)
            {
                ID3ArtistFrame artistFr = new ID3ArtistFrame(band);
                ID3AlbumFrame albumFr = new ID3AlbumFrame(album);
                ID3TitleFrame titleFr = new ID3TitleFrame(title);
                ID3GenreFrame genreFr = new ID3GenreFrame(genre);
                ID3YearFrame yearFr = new ID3YearFrame(year);

                artistFr.TextEncodingType = TextEncodingTypes.Unicode;
                albumFr.TextEncodingType = TextEncodingTypes.Unicode;
                titleFr.TextEncodingType = TextEncodingTypes.Unicode;
                genreFr.TextEncodingType = TextEncodingTypes.Unicode;
                yearFr.TextEncodingType = TextEncodingTypes.Unicode;

                myMp3.ID3v23Tag.Frames.Add(artistFr);
                myMp3.ID3v23Tag.Frames.Add(albumFr);
                myMp3.ID3v23Tag.Frames.Add(titleFr);
                myMp3.ID3v23Tag.Frames.Add(genreFr);
                myMp3.ID3v23Tag.Frames.Add(yearFr);

                myMp3.ID3v23Tag.WriteFlag = true;
                myMp3.Write();
            }

            // clean up local variables

               //         imageFrames.Clear();
            myMp3 = null;
        }
Example #60
0
        /// <summary>
        /// Returns the first image frame, if the parameter mp3 has any.
        /// </summary>
        private static Image GetExistingCover(string p_musicPath)
        {
            Image getImage = null;

            UltraID3 myMp3 = new UltraID3();
            myMp3.Read(p_musicPath);

            ID3FrameCollection myArtworkCollection =
                myMp3.ID3v23Tag.Frames.GetFrames(MultipleInstanceFrameTypes.Picture);

            if (myArtworkCollection.Count > 0)
            {
                ID3PictureFrame pf = (ID3PictureFrame)myArtworkCollection[0];

                Bitmap currCover = pf.Picture;

                // not sure why some pictures have size 0x0

                if (currCover != null)
                    getImage = currCover.GetThumbnailImage(currCover.Width, currCover.Height, null, IntPtr.Zero);
            }

            myMp3 = null;

            return getImage;
        }