示例#1
1
        /// <summary>
        /// Metodo encargado de buscarcanciones en una carpeta para su importaci'on en la biblioteca de usuario
        /// </summary>
        /// <param name="directoryPath">Ruta de acceso a directorio</param>
        public void ImportSongsToLibrary(String directoryPath)
        {
            List<TrackInfo> tracksToInsert = new List<TrackInfo>();
            SessionManager sessionManager= SessionManager.Instance;
            string unknownFrame = "Unknown";
            string[] musicFiles = Directory.GetFiles(directoryPath, "*.mp3");
            foreach (string musicFile in musicFiles)
            {
                UserTrackRepository userTrackRepository = new UserTrackRepository();
                TrackRepository trackRepository = new TrackRepository();

                using (var mp3 = new Mp3File(musicFile))
                {
                    TrackInfo currentTrack = new TrackInfo() {TrackId = Guid.NewGuid()};

                    if (mp3.HasTags)
                    {
                        Id3Tag tag = mp3.GetTag(Id3TagFamily.FileStartTag);
                        if (tag != null)
                        {
                            currentTrack.Title = tag.Title.IsAssigned ? tag.Title.Value : unknownFrame;
                            currentTrack.AlbumTitle = tag.Album.IsAssigned ? tag.Album.Value : unknownFrame;
                            currentTrack.ArtistTitle = tag.Artists.IsAssigned ? tag.Artists : unknownFrame;
                            currentTrack.Genre = getGenre(tag.Genre.Value);
                            if (tag.Lyrics.Count != 0)
                            {
                                currentTrack.Lyric = tag.Lyrics[0].IsAssigned ? tag.Lyrics[0].Lyrics : "";
                            }
                            else
                            {
                                currentTrack.Lyric = "";
                            }
                            if (tag.Year.IsAssigned)
                            {
                                int year;
                                if (Int32.TryParse(tag.Year.Value, out year))
                                {
                                    currentTrack.Year = year;
                                }
                            }
                        }
                        else
                        {
                            currentTrack.Title = unknownFrame;
                            currentTrack.AlbumTitle =unknownFrame;
                            currentTrack.ArtistTitle = unknownFrame;
                            currentTrack.Genre = unknownFrame;
                            currentTrack.Lyric = "";
                            currentTrack.Year = 0;
                        }
                                     
                        currentTrack.SongPath = musicFile;
                        currentTrack.TrackId = Guid.NewGuid();
                        tracksToInsert.Add(currentTrack);
                    }
                    else
                    {
                        currentTrack.Title =unknownFrame;
                        currentTrack.AlbumTitle = unknownFrame;
                        currentTrack.ArtistTitle =unknownFrame;
                        currentTrack.Genre = unknownFrame;
                        currentTrack.Lyric = "";
                        currentTrack.SongPath = musicFile;
                        currentTrack.TrackId= Guid.NewGuid();
                        currentTrack.Year = 0;
                        tracksToInsert.Add(currentTrack);
                    }
                }
            }
            this.userTracks.AddRange(tracksToInsert);
            this.InsertIntoDatabase(tracksToInsert);
        }
示例#2
0
        public async Task <List <Id3Tag> > GetFilesFromFolder()
        {
            var tagList = new List <Id3Tag>();

            var folderPicker = new FolderPicker
            {
                SuggestedStartLocation = PickerLocationId.Desktop,
                ViewMode = PickerViewMode.List
            };

            folderPicker.FileTypeFilter.Add(".mp3");

            var selectedFolder = await folderPicker.PickSingleFolderAsync();

            if (selectedFolder != null)
            {
                StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickerFolderToken", selectedFolder);
                await Task.Run(async() =>
                {
                    var files = await selectedFolder.GetFilesAsync();
                    foreach (var mediaFile in files)
                    {
                        var file = new Mp3File(mediaFile.Path, Mp3Permissions.ReadWrite);
                        tagList.Add(file.HasTagOfFamily(Id3TagFamily.Version2x) ? file.GetTag(Id3TagFamily.Version2x) : file.GetTag(Id3TagFamily.Version1x));
                        file.Dispose();
                    }
                });
            }

            return(tagList);
        }
示例#3
0
        private void WithID3_Net()
        {
            string[] musicFiles = Directory.GetFiles(txtFolderPath.Text, "*.mp3");
            foreach (string musicFile in musicFiles)
            {
                using (var mp3 = new Mp3File(musicFile, Mp3Permissions.ReadWrite))
                {
                    Console.WriteLine(musicFile);
                    Console.WriteLine(mp3.HasTagOfFamily(Id3TagFamily.FileStartTag).ToString());
                    var x   = this.GetValidVersion(mp3);
                    var tag = mp3.GetTag(x.Major, x.Minor);
                    Console.WriteLine("Title: {0}", tag.Title.Value);
                    Console.WriteLine("Artist: {0}", tag.Artists.Value);
                    Console.WriteLine("Album: {0}", tag.Album.Value);
                    Mp3Stream xs = new Mp3Stream(new MemoryStream());

                    mp3.WriteTag(tag, x.Major, x.Minor, WriteConflictAction.Replace);

                    foreach (var item in tag.Frames)
                    {
                        Console.WriteLine(item.ToString());
                    }
                    //Id3Tag tag = mp3.GetTag(Id3TagFamily.FileStartTag);
                    //Console.WriteLine("Title: {0}", tag.Title.Value);
                    //Console.WriteLine("Artist: {0}", tag.Artists.Value);
                    //Console.WriteLine("Album: {0}", tag.Album.Value);
                }
            }
        }
示例#4
0
        public void SaveAudio(string toLocation)
        {
            var ext    = System.IO.Path.GetExtension(_rawdata[(int)OSUfile.AudioFilename]);
            var toName = System.IO.Path.Combine(toLocation, GetSafeFilename(Title + ext));

            if (File.Exists(toName))
            {
                toName = System.IO.Path.Combine(toLocation, GetSafeFilename(Title + "[" + Version + "]" + ext));
            }
            File.Copy(Audio, toName, true);
            try
            {
                var file = new Mp3File(toName)
                {
                    TagHandler =
                    {
                        Artist = Artist,
                        Title  = Title
                    }
                };
                file.Update();
            }
            catch (Exception)
            {
                File.Copy(Audio, toName, true);
            }
        }
示例#5
0
        private void ButtonSave_Click(object sender, EventArgs e)
        {
            if (fileName != null)
            {
                Mp3File targetFile = new Mp3File(@fileName);

                try
                {
                    string artist = textBox1.Text;
                    string album  = textBox2.Text;
                    string song   = textBox3.Text;
                    string num    = textBox4.Text;
                    string genre  = textBox5.Text;
                    string year   = textBox6.Text;

                    targetFile.TagHandler.Artist = artist;
                    targetFile.TagHandler.Album  = album;
                    targetFile.TagHandler.Song   = song;
                    targetFile.TagHandler.Track  = num;
                    targetFile.TagHandler.Genre  = genre;
                    targetFile.TagHandler.Year   = year;

                    targetFile.UpdatePacked();
                    MessageBox.Show("Сохранено");
                }
                catch
                {
                    MessageBox.Show("Ошибка сохранения");
                }
            }
            else
            {
                MessageBox.Show("Нет файла");
            }
        }
示例#6
0
        private IEnumerable <Song> EnumerateSongs(string path)
        {
            var musicFiles = Directory.GetFiles(path, "*.mp3", SearchOption.AllDirectories);

            foreach (var musicFile in musicFiles)
            {
                using (var mp3 = new Mp3File(musicFile))
                {
                    var title    = string.Empty;
                    var artist   = string.Empty;
                    var duration = TimeSpan.Zero;
                    try
                    {
                        duration = mp3.Audio?.Duration ?? TimeSpan.Zero;
                        var tag = mp3.GetTag(Id3TagFamily.FileStartTag);
                        title  = tag?.Title?.Value ?? string.Empty;
                        artist = tag?.Artists?.Value ?? string.Empty;
                    }
                    catch (Exception)
                    {
                        Trace.WriteLine($"Error reading ID3 tag for: {musicFile}");
                    }

                    var songFileLen = (int)new FileInfo(musicFile).Length;
                    var song        = new Song(0, title, musicFile, artist, duration, File.GetLastWriteTime(musicFile),
                                               songFileLen);
                    yield return(song);
                }
            }
        }
        /// <summary>
        /// copy the newdata to the original.
        /// </summary>
        /// <param name="newData"></param>
        /// <param name="orig"></param>
        /// <returns>always true</returns>
        public static bool makeChangesAndContinue(TagHandlerUpdate newData, Mp3File orig)
        {
            newData.copy(orig.TagHandler);

            var retrycount = 0;
            var maxretry   = 10;

retry:
            try
            {
                orig.Update();
            }
            catch (Exception ecp)
            {
                retrycount++;
                if (retrycount >= maxretry)
                {
                    MessageBox.Show("Changes could not be made-" + ecp.ToString());
                    return(true);
                }
                System.Threading.Thread.Sleep(100);
                goto retry;
            }

            return(true);
        }
示例#8
0
        public ID3AdapterEdit(Mp3File mp3File)
        {
            _mp3File    = mp3File;
            _tagHandler = new TagHandler(_mp3File.TagModel);

            InitializeComponent();
        }
示例#9
0
 public void Rename(Mp3File file)
 {
     _timeMeasurer.Measure(() =>
     {
         file.MoveTo("NewName");
     }, "Mp3Renamer::Rename");
 }
示例#10
0
 private void dgvSongs_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
 {
     if (e.Button == MouseButtons.Right)
     {
         _song = dgvSongs.Rows[e.RowIndex].DataBoundItem as Mp3File;
     }
 }
示例#11
0
 public Musics(string path)
 {
     MusicFile = new Mp3File(path);
     try
     {
         OriginalTags = MusicFile.TagHandler;
         AcrTags      = new Mp3File(path).TagHandler;
         ApiTags      = new Mp3File(path).TagHandler;
         NewTags      = new Mp3File(path).TagHandler;
     } catch (NotImplementedException)
     {
         ((IErrorManager)Lookup.GetInstance().Get(typeof(IErrorManager))).NewError(ErrorCodes.id3v2_not_supported, MusicFile.FileName);
         OriginalTags = new TagHandler(new TagModel());
         AcrTags      = new TagHandler(new TagModel());
         ApiTags      = new TagHandler(new TagModel());
         NewTags      = new TagHandler(new TagModel());
     } catch (InvalidFrameException)
     {
         ((IErrorManager)Lookup.GetInstance().Get(typeof(IErrorManager))).NewError(ErrorCodes.invalid_encoding, MusicFile.FileName);
         OriginalTags = new TagHandler(new TagModel());
         AcrTags      = new TagHandler(new TagModel());
         ApiTags      = new TagHandler(new TagModel());
         NewTags      = new TagHandler(new TagModel());
     } catch (Exception)
     {
         ((IErrorManager)Lookup.GetInstance().Get(typeof(IErrorManager))).NewError(ErrorCodes.unknown, MusicFile.FileName);
         OriginalTags = new TagHandler(new TagModel());
         AcrTags      = new TagHandler(new TagModel());
         ApiTags      = new TagHandler(new TagModel());
         NewTags      = new TagHandler(new TagModel());
     }
     Logger.Instance.LoadFromDirectoryLog(this);
 }
示例#12
0
		private IEnumerable<Song> EnumerateSongs(string path)
		{
			var musicFiles = Directory.GetFiles(path, "*.mp3", SearchOption.AllDirectories);
			foreach (var musicFile in musicFiles)
			{
				using (var mp3 = new Mp3File(musicFile))
				{
					var title = string.Empty;
					var artist = string.Empty;
					var duration = TimeSpan.Zero;
					try
					{
						duration = mp3.Audio?.Duration ?? TimeSpan.Zero;
						var tag = mp3.GetTag(Id3TagFamily.FileStartTag);
						title = tag?.Title?.Value ?? string.Empty;
						artist = tag?.Artists?.Value ?? string.Empty;
					}
					catch (Exception)
					{
						Trace.WriteLine($"Error reading ID3 tag for: {musicFile}");
					}
					
					var songFileLen = (int)new FileInfo(musicFile).Length;
					var song = new Song(0, title, musicFile, artist, duration, File.GetLastWriteTime(musicFile),
						songFileLen);
					yield return song;
				}
			}
		}
示例#13
0
        public RollbackStatus Rollback()
        {
            if (_data.Count <= 0)
            {
                return(new RollbackStatus(RollbackState.Success));
            }

            var info = _data.Pop();

            //TODO: ROLLBACK
            try
            {
                var mp3 = new Mp3File(info.NewFileName, _saver);
                mp3.ChangeFileName(info.OldFileName);
                foreach (var tag in info.Tags)
                {
                    mp3[tag.Key] = tag.Value;
                }
                return(new RollbackStatus(RollbackState.Success));
            }
            catch (Exception e)
            {
                return(new RollbackStatus(RollbackState.Fail, e.Message));
            }
        }
示例#14
0
 public void Save()
 {
     using (var mp3 = new Mp3File(_file, Mp3Permissions.Write))
     {
         mp3.WriteTag(_tag, WriteConflictAction.NoAction);
     }
 }
示例#15
0
        private void ScanRepo(DirectoryInfo dir)
        {
            // Check if path exists and we can access the directory
            if (!dir.Exists)
            {
                return;
            }

            // walk through the files
            foreach (FileInfo file in dir.EnumerateFiles())
            {
                using (var mp3 = new Mp3File(file))
                {
                    Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2x);

                    Track track = new Track()
                    {
                        Title        = tag.Title,
                        Album        = new Album(tag.Album),
                        Artist       = new Artist(tag.Artists),
                        Repository   = _currentRepo,
                        RelativePath = _currentRepoUri.MakeRelativeUri(new Uri(file.FullName)).ToString()
                    };
                }


                //using (VisionServerContext db = new VisionServerContext())
                //{
                //    db.Tracks.AddAsync(track);
                //}
            }

            // walk through the directories
        }
示例#16
0
 public void DevTests()
 {
     using (var mp3 = new Mp3File(@"E:\Temp\Audio\BasicTagsWithImage.mp3", Mp3Permissions.ReadWrite))
     {
         mp3.DeleteAllTags();
         var tag        = new Id3Tag();
         var frontCover = new PictureFrame {
             Description = "The Front Cover",
             MimeType    = "image/jpg",
             PictureType = PictureType.FrontCover
         };
         frontCover.LoadImage(@"E:\Temp\Audio\FrontCover.jpg");
         tag.Pictures.Add(frontCover);
         var fileIcon = new PictureFrame {
             Description = "The File Icon",
             MimeType    = "image/png",
             PictureType = PictureType.Other
         };
         fileIcon.LoadImage(@"E:\Temp\Audio\MSN.png");
         tag.Pictures.Add(fileIcon);
         mp3.WriteTag(tag);
         foreach (Id3Frame frame in tag)
         {
             Console.WriteLine(frame);
         }
     }
 }
示例#17
0
        private bool VerificarArquivosEncontrados()
        {
            if (DiretorioRaiz != null)
            {
                ArrayList fileErro = new ArrayList();

                foreach (FileInfo file in DiretorioRaiz.GetFiles())
                {
                    using (var mp3 = new Mp3File(file))
                    {
                        if (mp3.GetTag(Id3TagFamily.Version1x) == null)
                        {
                            fileErro.Add(file);
                        }
                    }
                }

                if (fileErro.Count > 0)
                {
                    return(false);
                }
                return(true);
            }
            return(false);
        }
示例#18
0
        public void EditTag(string filename)
        {
            Mp3File mp3File = null;

            try
            {
                // create mp3 file wrapper; open it and read the tags
                mp3File = new Mp3File(filename);
            }
            catch (Exception e)
            {
                ExceptionMessageBox.Show(_form, e, "Error Reading Tag");
                return;
            }

            // create dialog and give it the ID3v2 block for editing
            // this is a bit sneaky; it uses the edit dialog straight out of TagScanner.exe as if it was a dll.
            TagEditor.ID3AdapterEdit id3Edit = new TagEditor.ID3AdapterEdit(mp3File);

            if (id3Edit.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    using (new CursorKeeper(Cursors.WaitCursor))
                    {
                        mp3File.Update();
                    }
                }
                catch (Exception e)
                {
                    ExceptionMessageBox.Show(_form, e, "Error Writing Tag");
                }
            }
        }
示例#19
0
        public IReadOnlyDictionary <string, string> ReadTags(string filePath)
        {
            var tags = new Dictionary <String, String>();

            if (!filePath.EndsWith(".mp3"))
            {
                throw new UnsupportedFileFormatException("Unsupported file format. Must be .mp3");
            }

            using (var mp3 = new Mp3File(filePath))
            {
                Id3Tag tag = mp3.GetTag(Id3TagFamily.FileStartTag);

                tags.Add("Album", tag.Album.Value);
                tags["Artist"] = tag.Artists.Value;

                StringBuilder sb = new StringBuilder();
                foreach (var value in tag.Comments)
                {
                    sb.AppendLine(value.Comment);
                }
                tags["Comments"] = sb.ToString();

                tags["TrackNo"] = tag.Track.Value;

                tags["DateReleased"] = tag.Year.Value;
            }

            return(tags.ToImmutableDictionary());
        }
示例#20
0
 public void Rename(Mp3File file)
 {
     if (_checker.CheckPermissions(file, _role))
     {
         _renamer.Rename(file);
     }
 }
示例#21
0
        public void selectNextItem(bool missingArt)
        {
            int currentIndex = FileList.SelectedIndex;

            bool exit       = false;
            bool invalidTag = false;

            while (exit == false && currentIndex > -1 && currentIndex < FileList.Items.Count)
            {
                invalidTag = false;
                currentIndex++;
                //open the file (peek at it, then close, to make sure we don't OOM
                FileInfo fi       = FileList.Items[currentIndex] as FileInfo;
                Mp3File  peekFile = new Mp3File(fi);


                //check for unsupported tags
                try
                {
                    if (peekFile.TagHandler.Picture == null)
                    {
                        //null test to see if the picture errors. Probably not needed
                    }
                }
                catch (NotImplementedException e)
                {
                    MessageBox.Show("Invalid tag on " + peekFile.FileName + " - " + e.Message);
                    invalidTag = true;
                }

                //if we are not looking for artwork, exit
                //or, if we have a valid tag, and it has a pic, exit

                if (missingArt) //looking for next file with missing artwork
                {
                    //skip invalid tags
                    if (!invalidTag && peekFile.TagHandler.Picture == null)
                    {
                        FileList.SelectedIndex = currentIndex;
                        exit = true;
                    }
                }
                else //looking for next valid file
                {
                    if (!invalidTag)
                    {
                        FileList.SelectedIndex = currentIndex;
                        exit = true;
                    }
                }


                //peekFile = null;
                //fi = null;
                //GC as the unmanaged code is a memory w***e
                GC.Collect(GC.MaxGeneration);
                GC.WaitForPendingFinalizers();
            }
        }
示例#22
0
 public void StubHandlerTests()
 {
     using (var mp3 = new Mp3File(@"E:\Temp\Abba - Fernando.mp3"))
     {
         Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2x);
         Console.WriteLine("{0}.{1}", tag.MajorVersion, tag.MinorVersion);
     }
 }
示例#23
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="mFileName">Mp3文件路径</param>
 public TagHelper(string mFileName)
 {
     this.mFileName = mFileName;
     //创建Mp3File对象
     mMp3File = new Mp3File(mFileName);
     //获取TagHandler
     mHandler = mMp3File.TagHandler;
 }
示例#24
0
        public async Task <bool> Download()
        {
            if (IsDownloading)
            {
                return(true);
            }

            DownloadCancellation = new CancellationTokenSource();
            DownloadTask         = Task.Run(async() =>
            {
                IsDownloading = true;

                try
                {
                    using (var response = await HttpWebRequest.CreateHttp(MP3URL).GetResponseAsync().ConfigureAwait(false))
                    {
                        MaxLenght = response.ContentLength;
                        using (var stream = response.GetResponseStream())
                        {
                            MP3FileName = string.Format("{0}_{1}_{2}.mp3", ShowName, Date, StartTime);
                            Mp3File     = await(await MixDataHandler.instance.GetFolder()).CreateFileAsync(MP3FileName, CreationCollisionOption.OpenIfExists);

                            using (MP3Stream = await Mp3File.OpenStreamForWriteAsync())
                            {
                                DownloadUpdateCancellation = new CancellationTokenSource();
                                DownloadUpdateTask         = Task.Run(() => CheckDownloadStatus(), DownloadUpdateCancellation.Token);

                                await stream.CopyToAsync(MP3Stream, 4096, DownloadUpdateCancellation.Token);
                            }
                        }
                    }

                    Downloaded = true;
                    fileSize   = (int)MaxLenght / 1024 / 1024;
                    NotifyPropertyChanged("FileSizeText");
                }
                catch (Exception)
                {
                    Downloaded = false;
                }
                finally
                {
                    IsDownloading        = false;
                    DownloadCancellation = null;
                    DownloadUpdateCancellation.Cancel();
                    DownloadUpdateCancellation = null;
                    MP3Stream      = null;
                    TimeDownloaded = DateTime.Now;
                    NotifyPropertyChanged("DownloadedOn");
                    MixDataHandler.instance.UpdateMix(this);
                    MediaPlayerViewModel.instance.CheckIfBackgroundTaskIsRunning();
                }

                return(Downloaded);
            }, DownloadCancellation.Token);

            return(await DownloadTask);
        }
示例#25
0
        public void refreshCurrentTag()
        {
            //setButtons(true);
            //loop through the selected files and grab the ID3 tags and info

            if (FileList.SelectedItems.Count > 0)
            {
                try
                {
                    FileInfo fi = FileList.SelectedItems[0] as FileInfo;

                    if (file != null)
                    {
                        file = null;
                    }

                    file          = new Mp3File(fi);
                    Tag_File.Text = fi.Name;


                    if (file.TagHandler.Picture != null)
                    {
                        SetImageFromBitmap(file.TagHandler.Picture, false);
                    }
                    else
                    {
                        Tag_Image.Source = null;
                    }
                    Tag_Album.Text  = file.TagHandler.Album;
                    Tag_Artist.Text = file.TagHandler.Artist;

                    Tag_Song.Text = file.TagHandler.Song;
                    imageUpdated  = false;
                    tagsUpdated   = false;

                    webFrame.Visibility = System.Windows.Visibility.Hidden;
                }
                catch (Id3Lib.Exceptions.TagNotFoundException)
                {
                    //drop out if no tag. Should still be able to write one.

                    file = null;
                }
                catch (System.IO.IOException)
                {
                    lbl_status.Text = "Error reading file.";
                }

                /*catch (Exception e)
                 * {
                 *  MessageBox.Show(e.ToString());
                 * }*/
            }
            else
            {
                //todo - lock fields
            }
        }
示例#26
0
        public void RenameWithoutPermissionChecker()
        {
            Mp3File     mp3File = new Mp3File();
            IMp3Renamer renamer = new Mp3Renamer(new TimeMeasurer());

            renamer.Rename(mp3File);

            Assert.AreEqual("NewName", mp3File.FullName);
        }
示例#27
0
        public void TryMakeTags()
        {
            var file = new Mp3File(@"Styx - Boat On The River.mp3");

            fileProcessor.MakeTags(file);

            Assert.AreEqual("Styx", file.Artist);
            Assert.AreEqual("Boat On The River", file.Title);
        }
示例#28
0
        /// <summary>
        /// Updates the song's information through its properties
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="song"></param>
        public static void UpdateSongInformation(string filePath, Song song)
        {
            Mp3File file = new Mp3File(filePath);

            file.TagHandler.Album  = song.Album;
            file.TagHandler.Artist = song.Artist;
            file.TagHandler.Title  = song.Title;
            file.Update();
        }
示例#29
0
        public void TryMakeTagsWithWrongFilename()
        {
            var file = new Mp3File("sample.mp3");
            var args = (new ArgumentParser()).Parse(new string[] { "*.mp3", "-recursive", "-toTag" });

            var renamer = new Renamer(args, "", new FileProcessor(new TestableFileSystem()));

            renamer.Rename(file);
        }
示例#30
0
        public void CheckRenamerWithTimeCounter()
        {
            var renamer = new RenamerWithTimeCounter(new FileRenamer());
            var file    = new Mp3File("SampleFile.mp3");

            renamer.Rename(file);

            Assert.AreNotEqual((new TimeSpan()).ToString(), renamer.Elapsed.ToString());
        }
示例#31
0
        public void CheckRenamerWithPermissionCheckAsUser()
        {
            var renamer = new RenamerWithPermissionCheck(new FileRenamer(), new PermissionChecker(), UserRole.User);
            var file    = new Mp3File("SampleFile.mp3");

            renamer.Rename(file);

            Assert.AreEqual("NewSampleFile.mp3", file.Path);
        }
示例#32
0
        public void CheckRenamer()
        {
            var renamer = new FileRenamer();
            var file    = new Mp3File("SampleFile.mp3");

            renamer.Rename(file);

            Assert.AreEqual("NewSampleFile.mp3", file.Path);
        }
示例#33
0
        //Re wrote this code for ID3 v3.24
        private void btnScanLatestVersion_Click(object sender, EventArgs e)
        {
            lstBoxEpisode.Items.Clear();
            string selectedFile = lstBox.SelectedItem.ToString();
            string mediaFile = mediaFolder + "\\" + selectedFile;

                using (var mp3 = new Mp3File(mediaFile))
                {
                    //New instance of fileinfo to retreive filesize
                    FileInfo f = new FileInfo(mediaFile);
                    long fileSize = f.Length;

                    //New instance of TagLib
                    TagLib.File file = TagLib.File.Create(mediaFile);
                    if (file.Tag.IsEmpty)
                    {
                        MessageBox.Show("File does not contain ID3 TAG");
                        return;
                    }

                    Id3Tag tag = mp3.GetTag(Id3TagFamily.FileStartTag);
                    lstBoxEpisode.Items.Add("Title: " + file.Tag.Title);
                    lstBoxEpisode.Items.Add("Description: " + file.Tag.Comment);
                    lstBoxEpisode.Items.Add("Duration: " + mp3.Audio.Duration);
                    lstBoxEpisode.Items.Add("Publish Date: " + tag.RecordingDate);
                    lstBoxEpisode.Items.Add("File: " + mediaFile);
                    //Deletion date needs adding
                    foreach (ICodec codec in file.Properties.Codecs)
                    {
                        lstBoxEpisode.Items.Add("Encoding: " + codec.Description);
                    }

                    lstBoxEpisode.Items.Add("File Size: " + fileSize);
                    lstBoxEpisode.Items.Add("Bit rate: " + mp3.Audio.Bitrate);

                }
            //}
        }
示例#34
0
        static void Write(string[] artists)
        {
            var defaultColor = System.Console.ForegroundColor;
            System.Console.ForegroundColor = ConsoleColor.Blue;
            
            foreach (var artist in artists)
            {
                var albums = Directory.GetDirectories(artist);
                foreach (var album in albums)
                {
                    var tracks = Directory.GetFiles(album, "*.mp3");
                    foreach (var track in tracks)
                    {
                        if (track.IsFormatValid())
                        {
                            try
                            {
                                using (var mp3file = new Mp3File(track, Mp3Permissions.ReadWrite))
                                {
                                    var artistName = track.ExtractArtistName();
                                    var tag = mp3file.GetTag(Id3TagFamily.Version2x);

                                    tag.Band.EncodingType = Id3TextEncoding.Unicode;
                                    tag.Band.Value = artistName;

                                    tag.Album.EncodingType = Id3TextEncoding.Unicode;
                                    tag.Album.Value = track.ExtractAlbumName();

                                    tag.Year.EncodingType = Id3TextEncoding.Unicode;
                                    tag.Year.Value = track.ExtractAlbumYear();

                                    tag.Title.EncodingType = Id3TextEncoding.Unicode;
                                    tag.Title.Value = track.ExtractTrackName();

                                    tag.Track.EncodingType = Id3TextEncoding.Unicode;
                                    tag.Track.Value = track.ExtractTrackNumber();

                                    tag.Artists.EncodingType = Id3TextEncoding.Unicode;
                                    tag.Artists.Value.Clear();
                                    tag.Artists.Value.Add(artistName);

                                    mp3file.WriteTag(tag);
                                }

                                System.Console.WriteLine("Tags wited to: " + track);
                            }
                            catch
                            {
                            }
                        }
                    }
                }
            }

            System.Console.ForegroundColor = defaultColor;
        }
示例#35
0
        // Used to remove records that no longer have existing files
        public int syncMusicFiles()
        {
            // Directories to add
            List<String> directories = new List<String>();
            directories.Add(@"D:\Music");
            directories.Add(@"D:\mp3s");

            // Get all files
            List<String> files = new List<String>();
            foreach (String directory in directories) {
                List<String> items = Directory.GetFiles(directory, "*.mp3", SearchOption.AllDirectories).ToList<String>();
                foreach(String item in items) {
                    files.Add(item);
                }
            }

            Debug.WriteLine("Found: " + files.Count + " Files");

            // Get ALL records in database
            List<MusicFile> rows = gdc.MusicFiles.ToList<MusicFile>();
            Debug.WriteLine(rows.Count());

            // Mark items for deletion
            foreach (MusicFile row in rows)
            {
                // If the physical file doesn't exist, remove it from the database
                if (!files.Contains(row.Filename))
                {
                    Debug.WriteLine("Deleting File: '" + row.Filename + "'");
                    gdc.MusicFiles.Remove(row);
                }
            }

            // Process deletion
            gdc.SaveChanges();

            // Edit existing records
            foreach (MusicFile row in rows)
            {
                // Skip files that don't already exist
                if (!files.Contains(row.Filename))
                {
                    continue;
                }

                // Get ID3 tag information
                Mp3File mp3 = new Mp3File(row.Filename);
                Id3Tag tag = mp3.GetTag(Id3TagFamily.FileStartTag);

                try {
                    // Set ID3 tag information
                    row.Title = tag.Title.Value;
                    row.Album = tag.Album.Value;
                    row.Artists = tag.Artists.Value;
                    row.Genres = tag.Genre.Value;
                    //row.Duration = mp3.Audio.Duration.ToString("g");

                    // Dispose object?
                    mp3.Dispose();

                    Debug.WriteLine("Editing file: '" + row.Filename + "'");
                    Debug.WriteLine("File Duration: '" + mp3.Audio.Duration.ToString("g") + "'");

                }
                catch (NullReferenceException e) {
                    // Remove problematic files
                    gdc.MusicFiles.Remove(row);
                }
            }

            // Get all filenames currently in the data set
            var existingFilenames = from row in rows
                                    select row.Filename;

            // Add new records
            foreach (String file in files)
            {
                // Skip adding items that already exist
                if(existingFilenames.Contains(file)) {
                    continue;
                }

                try
                {
                    // Get ID3 tag information
                    Mp3File mp3 = new Mp3File(file);
                    Id3Tag tag = mp3.GetTag(Id3TagFamily.FileStartTag);

                    // Set ID3 tag information
                    MusicFile mf = gdc.MusicFiles.Create();
                    mf.Id = Guid.NewGuid();
                    mf.Filename = file;
                    mf.Title = tag.Title.Value;
                    mf.Album = tag.Album.Value;
                    mf.Artists = tag.Artists.Value;
                    mf.Genres = tag.Genre.Value;
                    //mf.Duration = mp3.Audio.Duration.ToString("g");

                    // Dispose object?
                    mp3.Dispose();

                    // Add the new record
                    gdc.MusicFiles.Add(mf);

                    Debug.WriteLine("Adding file: '" + file + "'");
                }
                catch (Exception e) {
                    Debug.WriteLine("Unable to add file: '" + file + "'");
                }
            }

            // Write changes to database
            return gdc.SaveChanges();
        }
示例#36
0
        public bool initialize(String file)
        {
            filepath = file;

            int startpos = filepath.LastIndexOf("\\");
            if (startpos == -1)
                startpos = filepath.LastIndexOf("/");
            if (startpos == -1)
                startpos = 0;

            filename = filepath.Substring(startpos + 1, filepath.Length - startpos - 5);

            try {
                tagFile = File.Create(filepath);
                usingTagLib = true;
                return true;

            } catch (Exception ex) {
                Debug.WriteLine(filepath + " invalid. Trying ID3.");
                //Debug.WriteLine(ex.Message);
                usingTagLib = false;
            }

            try {
                using (Mp3File mp3 = new Mp3File(filepath, Mp3Permissions.ReadWrite)) {

                    id3Tag = mp3.GetTag(Id3TagFamily.FileStartTag);
                    try {

                        if (!String.IsNullOrWhiteSpace(id3Tag.Artists.Value)
                            && !String.IsNullOrWhiteSpace(id3Tag.Title.Value)) {

                            usingId3Tag = true;
                            return true;
                        }

                    } catch (Exception ex) {
                        Debug.WriteLine("Could not load ID3v2. Attempting v1");

                    }

                    try {

                        id3Tag = mp3.GetTag(Id3TagFamily.FileEndTag);
                        Debug.WriteLine("trying v1");

                        if (!String.IsNullOrWhiteSpace(id3Tag.Artists.Value)
                            && !String.IsNullOrWhiteSpace(id3Tag.Title.Value)) {

                            usingId3Tag = true;
                            return true;
                        }

                    } catch (Exception ex) {
                        Debug.WriteLine("Could not load v1!!!");
                        fileCorrupted = true;
                    }
                }
            } catch (Exception ex) {
                Debug.WriteLine("Problem with mp3. Likely Problem: incorrect filepath or name.");
                fileCorrupted = true;
            }
            return false;
        }
示例#37
0
        static void Main(string[] args)
        {
            var root = args[0];
            var newRoot = args[1];

            if (!Directory.Exists(root) || new DirectoryInfo(root) == new DirectoryInfo(newRoot))
            {
                Environment.Exit(1);
            }

            var warnings = 0;

            CheckCreateDirectory(newRoot);

            var logPath = Path.Combine(newRoot, "log.txt");
            using (var log = new StreamWriter(new FileInfo(logPath).Open(FileMode.Create)) { AutoFlush = true })
            {
                try
                {
                    var files = Directory.GetFiles(root, "*.mp3", SearchOption.AllDirectories);

                    foreach (var file in files)
                    {
                        using (var mp3 = new Mp3File(file))
                        {
                            var end = mp3.GetTag(Id3TagFamily.FileEndTag);
                            var tag = mp3.GetTag(Id3TagFamily.FileStartTag);

                            if (tag != null)
                            {
                                tag.MergeWith(end);
                            }
                            else
                            {
                                tag = end;
                            }

                            //log.WriteLine("{0,-3} | {1,-50} | {2,-50} | {3,-50}", start.Track.Value, start.Band.Value, start.Album.Value, start.Title.Value);

                            var bandPath = Path.Combine(newRoot, FixDirectoryPath(GetArtist(tag, log, file)));
                            CheckCreateDirectory(bandPath);

                            var albumPath = Path.Combine(bandPath, FixDirectoryPath(GetAlbum(tag, log, file)));
                            CheckCreateDirectory(albumPath);

                            var newFileName = FixFilePath(string.Format("{0} {1}.mp3", FixTrack(tag.Track), GetTitle(tag, log, file))).Trim();
                            var titlePath = Path.Combine(albumPath, newFileName);

                            if (!File.Exists(titlePath) || new FileInfo(file).Length == new FileInfo(titlePath).Length)
                            {
                                File.Copy(file, titlePath, true);

                                using (var newMp3 = new Mp3File(titlePath, Mp3Permissions.ReadWrite))
                                {
                                    Thread.Sleep(TimeSpan.FromMilliseconds(1));

                                    newMp3.DeleteAllTags();
                                    newMp3.WriteTag(tag, WriteConflictAction.Replace);
                                }

                                //log.WriteLine("File '{0}' copied to '{1}'", file, albumPath);
                            }
                            else
                            {
                                log.WriteLine("*** WARNING: File '{0}' already exists with different length", titlePath);
                                warnings++;
                            }
                        }

                        Console.Write('.');
                    }

                    log.WriteLine();
                    log.WriteLine("Ready with {0} warning(s)", warnings);

                    log.WriteLine();

                    var newFiles = Directory.GetFiles(newRoot, "*.mp3", SearchOption.AllDirectories);
                    log.WriteLine("Started with {0} MP3 files, ended up with {1}.", files.Length, newFiles.Length);
                }
                catch (Exception exception)
                {
                    log.WriteLine();
                    log.WriteLine("*** ERROR: {0}", exception.Message);
                    log.WriteLine(exception.StackTrace);
                }

                Process.Start(logPath);
            }
        }
示例#38
0
 public void Rename(string newName)
 {
     _mp3File.Dispose();
     var newFilePath = FilePath.Replace(FileName + ".mp3", newName + ".mp3");
     if(File.Exists(newFilePath))
         throw new Exception("File exist");
     File.Move(FilePath,newFilePath);
     FilePath = newFilePath;
     FileName = newName;
     _mp3File = new Mp3File(FilePath,Mp3Permissions.ReadWrite);
 }