Example #1
0
        public static void SetFileTags(Mp3File file, Mp3Tag data)
        {
            if (data != null)
            {
                using (var mp3 = new Mp3(file.FilePath, Mp3Permissions.ReadWrite))
                {
                    Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2X);

                    if (tag == null)
                    {
                        tag = new Id3Tag();
                        var propinfo = typeof(Id3Tag).GetProperty("Version", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
                        propinfo.SetValue(tag, Id3Version.V23);
                    }

                    tag.Artists.Value.Add(data.Artist);
                    tag.Title = new TitleFrame(data.Title);
                    tag.Album = new AlbumFrame(data.Album);
                    tag.Year  = new YearFrame(data.Year);

                    if (tag.Genre.Value != null)
                    {
                        string filteredGenre = string.Join(';', tag.Genre.Value.Split(';').Where(x => FilterGenre(x)));
                        tag.Genre = new GenreFrame(filteredGenre);
                    }

                    mp3.WriteTag(tag, WriteConflictAction.Replace);

                    file.Filled = true;

                    Console.WriteLine($"{data.Artist}\t{data.Title}\t{data.Album}\t{data.Year}\t{data.Genres}");
                }
            }
        }
Example #2
0
        /// <summary>
        /// Generates a m3u file with all mp3 files in the specified directory
        /// </summary>
        /// <param name="mp3Directory"></param>
        /// <param name="m3uName">The optional name of the m3u file. If not specified, the name of the directory containing the mp3 files is used.</param>
        /// <param name="m3uDirectory">The optional directory where the m3u file is created. If not specified, the m3u file is created in the directory containing the mp3 files.</param>
        public void CreateM3u(string mp3Directory, string m3uName = null, string m3uDirectory = null)
        {
            var directoryInfo = new DirectoryInfo(mp3Directory);

            string m3uFilename = String.IsNullOrEmpty(m3uName) ? directoryInfo.Name : m3uName;

            m3uFilename = Path.ChangeExtension(m3uFilename, ".m3u");

            string m3uDirectoryName = String.IsNullOrEmpty(m3uDirectory) ? mp3Directory : m3uDirectory;

            Directory.CreateDirectory(m3uDirectoryName);

            string m3uFile = Path.Combine(m3uDirectoryName, m3uFilename);


            using (var m3u = new StreamWriter(m3uFile, false))
            {
                m3u.WriteLine("#EXTM3U");

                foreach (string mp3File in Directory.EnumerateFiles(mp3Directory, "*.mp3", SearchOption.AllDirectories))
                {
                    String mp3FileRelative = Path.GetRelativePath(m3uDirectoryName, mp3File);

                    using (var mp3 = new Mp3(mp3File))
                    {
                        Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2X);

                        m3u.WriteLine($"#EXTINF:{tag.Length.Value.TotalSeconds:F0},{tag.Artists.Value.FirstOrDefault() ?? ""} - {tag.Title}");
                        m3u.WriteLine(mp3FileRelative);
                    }
                }
            }
        }
Example #3
0
        private static void EditFile(string fileName)
        {
            Console.WriteLine(fileName);
            var dados = Path.GetFileNameWithoutExtension(fileName);

            if (dados.IndexOf("-") == -1)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("    Above file was ignored, isn't the match pattern Artist - Title.");
                Console.ResetColor();
                return;
            }

            using (var mp3 = new Mp3(fileName, Mp3Permissions.ReadWrite))
            {
                mp3.DeleteAllTags();
                var tag      = new Id3Tag();
                var propinfo = typeof(Id3Tag).GetProperty("Version", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
                propinfo.SetValue(tag, Id3Version.V23);
                tag.Artists.Value.Clear();
                tag.Artists.Value.Add(dados.Substring(0, dados.IndexOf("-") - 1).Trim());
                tag.Title.Value = dados.Substring(dados.IndexOf("-") + 1, dados.Length - (dados.IndexOf("-") + 1)).Trim();
                mp3.WriteTag(tag, WriteConflictAction.Replace);
            }
        }
Example #4
0
        static void Main(string[] args)
        {
            File f = new File("file_1.doc", 256);

            Console.WriteLine(f.ToString());
            Mp3 m = new Mp3("Music.mp3", 12);

            Console.WriteLine(m.ToString());
            Archive a = new Archive("Lab4.rar", 3);

            Console.WriteLine(a.ToString());
            Directory d = new Directory("Windows");

            Console.WriteLine(d.ToString());
            d.create(f);
            d.create(f);
            d.create(m);
            d.create(a);
            d.create(m);
            d.create(m);
            Console.WriteLine(d.ToString());
            Console.WriteLine("Volume directory: " + d.GetVolume());
            int x = d.KolAudio();

            Console.WriteLine("Kolichestvo audio: " + x);
            f.RunFile();

            Directory d1 = new Directory("D1");

            d1.create(f);
            Console.WriteLine(d1.ToString());
            d.create(d1);
            Console.WriteLine(d.ToString());
        }
Example #5
0
        public void GetTagsTest()
        {
            var test = new Mp3(@"K:\music\40㍍P\41m\恋愛裁判.mp3");

            test.GetTags();
            //Assert.Fail();
        }
Example #6
0
        private void lblAnswer_Click(object sender, EventArgs e)
        {
            var    mp3 = new Mp3(Victorina.answer);
            Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2X);

            lblAnswer.Text = tag.Artists + " - " + tag.Title;
        }
Example #7
0
        /// <summary>
        /// Metoda pokazująca urządzenie oraz specyfikację w nowym oknie
        /// </summary>
        /// <param name="mp3"></param>
        public void ShowDevice(Mp3 mp3)
        {
            Mp3Form mp3Form = new Mp3Form();

            mp3Form.Show();
            mp3Form.FillDataGridView(mp3.DiskSizeGb, mp3.NumberOfFormats, mp3.FmRadio, mp3.HeadphoneJack, mp3.TimeOfPlayingMusic);
        }
Example #8
0
 public void Save()
 {
     using (var mp3 = new Mp3(_file, Mp3Permissions.Write))
     {
         mp3.WriteTag(_tag, WriteConflictAction.NoAction);
     }
 }
Example #9
0
 public void ImportPaths(params string[] paths)
 {
     if (paths.Any(p => checkExtension(Path.GetExtension(p))))
     {
         return;
     }
     foreach (string p in paths)
     {
         AudioMetadata meta = new AudioMetadata();
         using (var mp3 = new Mp3(p))
         {
             Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2X);
             if (tag.CustomTexts.Count > 0 && tag.CustomTexts.Any(t => t.Value.StartsWith("DISPLAY ARTIST\0")))
             {
                 meta.Artist = meta.ArtistUnicode = tag.CustomTexts.First(t => t.Value.StartsWith("DISPLAY ARTIST\0")).Value.Split("DISPLAY ARTIST\0")[1];
             }
             else if (tag.Artists.Value.Count > 0)
             {
                 meta.Artist = meta.ArtistUnicode = tag.Artists.Value[0];
             }
             else
             {
                 meta.Artist = meta.ArtistUnicode = "Unkown Artist";
             }
             meta.Title = meta.TitleUnicode = tag.Title.Value ?? "Unkown Title";
         }
         playlist.AddSong(meta, p);
     }
 }
Example #10
0
 public void GetTagsTest()
 {
     try {
         var test   = new Mp3(@"D:\CloudMusic\初音ミク\Re:Start\wowaka,初音ミク - アンノウン・マザーグース.mp3");
         var result = test.GetTags();
         var r      = test.BeginGetTags().Result;
     } catch { Assert.Fail(); }
 }
Example #11
0
        public Mp3Info(FileInfo fileInfo)
        {
            FileInfo = fileInfo;

            using (var mp3 = new Mp3(fileInfo.FullName))
            {
                Tag = mp3.GetTag(Id3TagFamily.Version2X);
            }
        }
Example #12
0
 public void Init(string file, IOutput output)
 {
     _output = output;
     _file   = file;
     using (var mp3 = new Mp3(file, Mp3Permissions.Read))
     {
         _tag = mp3.GetTag(Id3TagFamily.Version2X);
     }
     _encoding = (_tag.Version == Id3Version.V23 || _tag.Version == Id3Version.V1X) ? Id3TextEncoding.Unicode : (Id3TextEncoding)03;//TODO: Should be changed to utf-8 when implemented
 }
Example #13
0
        static void Main(string[] args)
        {
            string[] filePaths = Directory.GetFiles("media");

            ArrayList PIList = new ArrayList();

            foreach (string path in filePaths)
            {
                string type = path.Substring(path.Length - 4, 4);
                string name = path.Substring(6, path.Length - 10);

                PIList.Add(new PlayerItem(path, name, type));
            }

            for (int i = 0; i < PIList.Count; i++)
            {
                Console.WriteLine($"{i + 1} - {((PlayerItem)PIList[i]).Name}{((PlayerItem)PIList[i]).Type}");
            }
            Console.WriteLine();
            Console.WriteLine("Выберите музыку по индексу");
            byte index = Convert.ToByte(Console.ReadLine());

            PlayerItem chosen = ((PlayerItem)PIList[index - 1]);

            Mp3 mp3 = new Mp3(chosen);
            Wav wav = new Wav(chosen);
            Mkv mkv = new Mkv(chosen);

            switch (chosen.Type)
            {
            case ".mkv":
                mkv.Play();
                mkv.Pause();
                mkv.Stop();
                break;

            case ".mp3":
                mp3.Play();
                mp3.Pause();
                mp3.Stop();
                break;

            case ".wav":
                wav.Play();
                wav.Pause();
                wav.Stop();
                wav.Record();
                break;

            default:
                Console.WriteLine("расширение не поддерживается");
                break;
            }
            Console.ReadKey();
        }
        public static void Main(string[] args)
        {
//            foreach (var item in DirectoryFileLister.ListFiles(
//                @"G:\DK-HP-PA-2000AR\Songs\Records\Pitbull\Global Warming"))
//                Console.WriteLine(item);

//            DirectoryFileLister.ListFiles(@"G:\DK-HP-PA-2000AR\Songs\Records\Pitbull\Global Warming").ForEach(item =>
//            {
//                if (item.Contains(".mp3"))
//                {
//                    Console.WriteLine(item);
//                }
//            });

            const string folder = @"D:\Global Warming";

            DirectoryFileLister.ListFiles(folder).ForEach(songFile =>
            {
                var songFileInfo = new FileInfo(songFile);
                if (!songFileInfo.Extension.Equals(".mp3"))
                {
                    return;
                }

                Console.WriteLine("Song : " + songFile);

                var tag = new Mp3(songFile).GetTag(Id3TagFamily.Version2X);
                Console.WriteLine("Title: {0}", tag.Title);
                Console.WriteLine("Artist: {0}", tag.Artists);
//                Console.WriteLine("Album: {0}", tag.Album);

                var songTitle       = tag.Title.ToString().Trim();
                var songArtist      = tag.Artists.ToString().Trim();
                var newSongFileBase = folder + "\\" + songTitle + " - " + songArtist;
                Console.WriteLine("New Song File Base : " + newSongFileBase);
                var newSongFile = newSongFileBase + songFileInfo.Extension;

//                var fileService=new FileService(new FileManagerConfig());
//                fileService.Rename(songFileInfo.Name+songFileInfo.Extension,folder,newSongFileBase+songFileInfo.Extension,DirectoryType.File);
//                File.Move(file, newFileBase + ".mp3");

                var lyrics = songFileInfo.Name + ".lrc";
                if (!File.Exists(lyrics))
                {
                    return;
                }

                Console.WriteLine("Lyrics : " + lyrics);
                var newLyricsFile = newSongFileBase + ".lrc";
//                fileService.Rename(lyrics,folder,newSongFileBase+".lrc",DirectoryType.File);
//                File.Move(lyrics, newFileBase + ".lrc");
            });
        }
Example #15
0
        private void txtSearch_TextChanged(object sender, TextChangedEventArgs e)
        {
            System.Windows.Controls.TextBox t = (System.Windows.Controls.TextBox)sender;
            string filter = t.Text;

            if (startSelectWatch)
            {
                ICollectionView cv = CollectionViewSource.GetDefaultView(MusicDataFile.ItemsSource);
                if (filter == "")
                {
                    cv.Filter = null;
                }
                else
                {
                    cv.Filter = o =>
                    {
                        Mp3 p = o as Mp3;
                        if (t.Name == "txtId")
                        {
                            return(p.Title == filter);
                        }
                        //return (p.Title.ToUpper().StartsWith(filter.ToUpper()));

                        switch (cbSearchTarget.Text)
                        {
                        case "Title":
                            return(p.Title.ToUpper().Contains(filter.ToUpper()));

                        case "FileName":
                            return(p.FileName.ToUpper().Contains(filter.ToUpper()));

                        case "Album":
                            return(p.Album.ToUpper().Contains(filter.ToUpper()));

                        case "Artist":
                            return(p.Artist.ToUpper().Contains(filter.ToUpper()));

                        case "Year":
                            return(p.Year.ToString().Contains(filter.ToString()));

                        case "Genres":
                            return(p.Genres.ToUpper().Contains(filter.ToUpper()));

                        case "Location":
                            return(p.Location.ToUpper().Contains(filter.ToUpper()));

                        default:
                            return(p.FileName.ToUpper().Contains(filter.ToUpper()));
                        }
                    };
                }
            }
        }
Example #16
0
        private static Displayable MapToMp3(ElasticTitleIndex elasticProduct, Displayable displayable)
        {
            var mp3 = new Mp3
            {
                Narrators  = elasticProduct.Narrator,
                StockLevel = elasticProduct.StockLevel,
                MediaCount = elasticProduct.MediaCount,
            };
            Book book = (Book)mp3;

            displayable = MapBookToDisplayable(elasticProduct, book);
            return(displayable);
        }
Example #17
0
        private RenameSuggestion GetRenameSuggestion(string filePath)
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                return(new RenameSuggestion(filePath, filePath, FileNamerMessages.InvalidFilePath));
            }

            if (!File.Exists(filePath))
            {
                return(new RenameSuggestion(filePath, filePath, FileNamerMessages.MissingFile));
            }

            string directory    = Path.GetDirectoryName(filePath);
            string originalName = Path.GetFileName(filePath);

            using (var mp3 = new Mp3(filePath))
            {
                Id3Tag tag = mp3.GetTag(Id3Version.V23);
                if (tag == null)
                {
                    return(new RenameSuggestion(directory, originalName, FileNamerMessages.MissingId3v23TagInFile));
                }

                //TODO: Get ID3v1 tag as well and merge with the v2 tag

                string newName = GetNewName(tag, originalName, out string missingFrameName);

                if (missingFrameName != null)
                {
                    return(new RenameSuggestion(directory, originalName,
                                                string.Format(FileNamerMessages.MissingDataForFrame, missingFrameName)));
                }

                newName += ".mp3";
                RenamingEventArgs renamingEventResult = FireRenamingEvent(tag, originalName, newName);
                if (renamingEventResult.Cancel)
                {
                    return(new RenameSuggestion(directory, originalName, RenameStatus.Cancelled));
                }

                newName = renamingEventResult.NewName;

                RenameStatus status = originalName.Equals(newName, StringComparison.Ordinal)
                    ? RenameStatus.CorrectlyNamed : RenameStatus.Rename;
                return(new RenameSuggestion(directory, originalName, newName, status));
            }
        }
Example #18
0
        public (Dictionary <string, List <string> >, string[]) GetId3Lylics(string fileDiretory)
        {
            Dictionary <string, List <string> > dicMusics = new Dictionary <string, List <string> >();

            string[] musicFiles = Directory.GetFiles(fileDiretory, "*.mp3");
            foreach (string musicFile in musicFiles)
            {
                using (var mp3 = new Mp3(musicFile))
                {
                    Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2X);

                    dicMusics.Add(tag.Title, tag.Lyrics.ToList().Select(d => d.Lyrics).ToList());
                }
            }

            return(dicMusics, musicFiles);
        }
Example #19
0
        private void Play(string file)
        {
            if (state == State.NaN || state == State.Stop)
            {
                try
                {
                    var t    = new AudioFileReader(file).TotalTime;
                    var time = Math.Floor(t.TotalSeconds);
                    TimeTotal.Text     = t.ToString(@"mm\:ss");
                    TimeSlider.Maximum = time;
                }
                catch (Exception e)
                {
                    var mp3File = new Mp3(file);
                    var t       = mp3File.Audio.Duration;
                    var time    = Math.Floor(t.TotalSeconds);
                    TimeTotal.Text     = t.ToString(@"mm\:ss");
                    TimeSlider.Maximum = time;
                }
                TimeSlider.Value = 0;
                Player.Open(new Uri(file));
                Player.SpeedRatio  = 1;
                Player.MediaEnded += (o, e) => Stop(null, null);
                Timer.Interval     = TimeSpan.FromSeconds(0.5);
                Timer.Tick        += (o, e) =>
                {
                    TimeNow.Text = Player.Position.ToString(@"mm\:ss");
                    var now = Player.Position.TotalSeconds;
                    PChange          = true;
                    TimeSlider.Value = now;
                    PChange          = false;
                };

                Timer.Start();
                Player.Play();

                Player.Volume -= 0.02;
                Player.Volume += 0.02;

                state             = State.Play;
                PausePlay.Content = "Пауза";
                TimeNow.Text      = "00:00";
            }
        }
Example #20
0
        public void AddSong(AudioMetadata meta, string path)
        {
            string number = $"{ metadataList.Count + 1}";
            string s      = "";

            using (var mp3 = new Mp3(path))
            {
                Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2X);
                if (tag.Pictures.Count > 0)
                {
                    s = tag.Pictures[0].GetExtension();
                    if (s == "jpeg" || s == "jpg")
                    {
                        s = ".jpg";
                    }
                    else if (s == "png")
                    {
                        s = ".png";
                    }
                    using (var ds = storage.GetStream($"{number}{s}", FileAccess.Write, FileMode.Create))
                        tag.Pictures[0].SaveImage(ds);
                }
            }
            meta.CoverFiles.Add($"{number}{s}");
            using (var d = new FileStream(path, FileMode.Open))
            {
                using (var e = storage.GetStream($"{number}{Path.GetExtension(path)}", FileAccess.Write, FileMode.Create))
                {
                    byte[] arr = new byte[d.Length];
                    d.Read(arr, 0, arr.Length);
                    e.Write(arr, 0, arr.Length);
                }
            }
            meta.AudioFile = $"{number}{Path.GetExtension(path)}";
            metadataList.Add(meta);
            using (StreamWriter stream = new StreamWriter(storage.GetStream($"{number}.json", FileAccess.ReadWrite, FileMode.Create)))
                stream.Write(JsonConvert.SerializeObject(meta, Formatting.Indented));
            using (StreamWriter mainFile = new StreamWriter(storage.GetStream("list.json", FileAccess.Write, FileMode.Create)))
                mainFile.Write(JsonConvert.SerializeObject(metadataList, Formatting.Indented));
            if (!(proyect.Metadata.Value?.Track.IsRunning ?? false))
            {
                PlayNext();
            }
        }
Example #21
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Get all the files that are mp3
            string[] FileList = Directory.GetFiles(txtSource.Text, "*.mp3", SearchOption.AllDirectories);
            foreach (string originalFile in FileList)
            {
                var file = new Mp3(originalFile);

                Id3Tag tags = file.GetTag(Id3TagFamily.Version2X);

                string artist        = tags.Artists;
                string fullAlbumDesc = $"{tags.Year.Value} - {tags.Album.Value}";
                string fileName      = RemoveInvalidChars($"{tags.Track.Value} - {tags.Title.Value}.mp3");
                string destination   = $"{fdgDestination.SelectedPath}//{artist}//{fullAlbumDesc}//{fileName}";

                System.IO.Directory.CreateDirectory(destination);
                System.IO.File.Copy(originalFile, destination);
            }
        }
Example #22
0
            protected void ParseName(int track, string sourceFile)
            {
                int snipLen = 15;

                DisplayName = new FileInfo(sourceFile).Name;
                try
                {
                    var tag = new Mp3(sourceFile, Mp3Permissions.Read).GetAllTags().FirstOrDefault();
                    if (tag != null && tag.Title.IsAssigned)
                    {
                        DisplayName = tag.Title.Value;
                    }
                }
                catch (Exception ex)
                {
                }

                ShortName = DisplayName.PadRight(snipLen).Substring(0, snipLen);
            }
Example #23
0
        protected static void LoadMp3(Dictionary <string, string> param, IList <VFile> files, Dictionary <int, Folder> albumsKeyValue, int audioCount)
        {
            // второй уровень
            int countOnStep = 500; // Сколько забирать за шаг
            int pageCount   = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(audioCount) / countOnStep));

            Dictionary <string, string> paramSend = new Dictionary <string, string>(param)
            {
                { "count", countOnStep.ToString() },
                { "offset", "0" }
            };

            for (int page = 0; page < pageCount; page++)
            {
                paramSend["offset"] = (page * countOnStep).ToString();
                JObject apiRequest = (JObject)VKAPI.Vkapi.Instance.StartTaskSync(new VKAPI.ApiQuery("audio.get", paramSend));
                JArray  items      = (JArray)apiRequest.GetValue("items");
                foreach (JToken item in items)
                {
                    var audio = item.ToObject <SerializationObject.Audio>();
                    var finfo = new Mp3(audio);
                    if (albumsKeyValue.Count == 0)
                    {
                        files.Add(finfo);
                    }
                    else
                    {
                        albumsKeyValue[0].ChildsAdd(finfo);
                        if (audio.AlbumId != 0)
                        {
                            // Здесь ньюанс, в ChildsAdd есть уникальность которая изменяет имя.
                            // Но так как в общий список мы добавляем первым, то имя файла будет уникальное всегда
                            albumsKeyValue[audio.AlbumId].ChildsAdd(finfo);
                        }
                    }
                }
            }

            foreach (var folder in albumsKeyValue.Values)
            {
                folder.IsLoaded = true;
            }
        }
Example #24
0
 public static Mp3Tag GetFileTags(string filePath)
 {
     using (var mp3 = new Mp3(filePath, Mp3Permissions.Read))
     {
         Id3Tag tag;
         if (mp3.HasTagOfFamily(Id3TagFamily.Version1X))
         {
             tag = mp3.GetTag(Id3TagFamily.Version1X);
         }
         else
         {
             tag = mp3.GetTag(Id3TagFamily.Version2X);
         }
         if (tag != null)
         {
             return(new Mp3Tag(tag));
         }
         return(null);
     }
 }
Example #25
0
 public Song(string path)
 {
     this.path = path;
     try
     {
         var    mp3 = new Mp3(path);
         Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2X);
         this.Name      = tag.Title;
         this.Album     = tag.Album;
         this.Singer    = tag.Artists;
         this.Thumbnail = LoadImage(tag.Pictures[0].PictureData);
     }
     catch (Exception)
     {
         if (this.Name == "Unknown")
         {
             GetNameFromPath();
         }
     }
 }
Example #26
0
        static void Main(string[] args)
        {
            Console.WriteLine("Files path?");
            string filesPath = Console.ReadLine();

            string[] folders = Directory.GetDirectories(filesPath);
            //string[] files = Directory.GetFiles(filesPath, "*.mp3", SearchOption.AllDirectories);
            Array.Sort(folders, StringComparer.InvariantCulture);
            int count = 1;

            foreach (string folder in folders)
            {
                string folderName = new DirectoryInfo(folder).Name;
                Console.WriteLine("Processing - " + folder);
                string[] files = Directory.GetFiles(folder, "*.mp3");
                foreach (string file in files)
                {
                    Console.WriteLine(count.ToString() + " - " + file);
                    using (var mp3 = new Mp3(file, Mp3Permissions.ReadWrite))
                    {
                        Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2X);
                        if (tag == null)
                        {
                            tag = new Id3Tag();
                            //tag.Version = Id3Version.V23;
                            // version is internal set, but if we use reflection to set it, the mp3.WriteTag below works.
                            var propinfo = typeof(Id3Tag).GetProperty("Version", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
                            propinfo.SetValue(tag, Id3Version.V23);
                        }
                        tag.Track.Value = count;
                        //tag.Album.Value = count.ToString();
                        mp3.WriteTag(tag, WriteConflictAction.Replace);
                        string fileId   = GetFileId(count);
                        string fileName = new FileInfo(file).Name;
                        File.Copy(file, filesPath + @"/" + fileId + "_" + folderName + "_" + fileName);
                    }
                    count++;
                }
            }
            Console.ReadLine();
        }
Example #27
0
    public static AudioClip GetAudio(string path)
    {
        string extension = Path.GetExtension(path);

        byte[] data = File.ReadAllBytes(path);
        switch (extension)
        {
        case ".mp3":
        {
            return(Mp3.GetMp3Audio(Path.GetFileName(path), data));
        }

        case ".wav":
            return(WavUtility.ToAudioClip(data));

        default:
        {
            Debug.Log(extension + " file type is not yet supported");
            return(null);
        }
        }
    }
Example #28
0
        static void Main()
        {
            var directories = Directory.EnumerateDirectories(DirectoryPath);

            foreach (var dir in directories)
            {
                if (DirectoryHasAudioFiles(dir))
                {
                    var files = Directory.GetFiles(dir).Where(f => f.EndsWith("mp3"));
                    var oldFileNamesToNewFileNames = new Dictionary <string, string>();
                    foreach (var file in files)
                    {
                        using var mp3 = new Mp3(file);
                        var tagV1    = mp3.GetTag(Id3TagFamily.Version1X);
                        var tagV2    = mp3.GetTag(Id3TagFamily.Version2X);
                        var fileInfo = new FileInfo(file);

                        Id3Tag tag = tagV1 ?? tagV2;

                        if (tag == null || fileInfo.Name == $"{tag.Title}.mp3")
                        {
                            continue;
                        }
                        var newName = $"{ReplaceInvalidChars(tag.Title)}.mp3";
                        oldFileNamesToNewFileNames.Add(Path.Combine(dir, fileInfo.Name), Path.Combine(dir, newName));
                    }

                    if (oldFileNamesToNewFileNames.Count > 0)
                    {
                        Console.WriteLine("About to rename some files. Hang on!");
                        foreach (var(oldFileName, newFileName) in oldFileNamesToNewFileNames)
                        {
                            File.Move(oldFileName, newFileName);
                        }
                    }
                }
            }
            Console.WriteLine("All done!");
        }
Example #29
0
        private static void MainProcess(Mp3 mp3, string mp3Path, string[] images)
        {
            var tag = mp3.GetTag(Id3TagFamily.Version2X);

            if (tag == null)
            {
                tag = new Id3Tag();
                if (!mp3.WriteTag(tag, Id3Version.V23, WriteConflictAction.Replace))
                {
                    ShowError($"Failed to create tag to mp3 file.");
                }
            }

            // ask option
            bool addCover;
            bool removeFirst;
            var  originCoverCount = tag.Pictures.Count;

            if (originCoverCount == 0)
            {
                var ok = MessageBoxEx.Show($"There is no cover in the given mp3 file, would you want to add the given {images.Length} cover(s) to this mp3 file?",
                                           MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation, new string[] { "&Add", "&Cancel" });
                addCover    = ok == DialogResult.OK;
                removeFirst = false;
            }
            else
            {
                var ok = MessageBoxEx.Show($"The mp3 file has {originCoverCount} cover(s), would you want to remove it first, and add the given {images.Length} cover(s) to this mp3 file?",
                                           MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation, new string[] { "&Replace", "&Append", "&Cancel" });
                addCover    = ok != DialogResult.Cancel;
                removeFirst = ok == DialogResult.Yes;
            }

            // handle tag
            if (!addCover)
            {
                return;
            }
            if (removeFirst)
            {
                tag.Pictures.Clear();
            }
            foreach (var image in images)
            {
                var extension = Path.GetExtension(image).ToLower();
                var mime      = "image/";
                if (extension == ".png")
                {
                    mime = "image/png";
                }
                else if (extension == ".jpg" || extension == ".jpeg")
                {
                    mime = "image/jpeg";
                }
                var newCover = new PictureFrame()
                {
                    PictureType = PictureType.FrontCover,
                    MimeType    = mime
                };
                try {
                    newCover.LoadImage(image);
                } catch (Exception ex) {
                    ShowError($"Failed to load image: \"{image}\". Details:\n{ex}");
                    return;
                }
                tag.Pictures.Add(newCover);
            }

            // write tag
            mp3.DeleteTag(Id3TagFamily.Version2X);
            if (!mp3.WriteTag(tag, Id3Version.V23, WriteConflictAction.Replace))
            {
                ShowError($"Failed to write cover(s) to mp3 file.");
                return;
            }

            string msg;

            if (removeFirst)
            {
                msg = $"Success to remove {originCoverCount} cover(s) and add {images.Length} cover(s) to mp3 file \"{mp3Path}\".";
            }
            else if (originCoverCount != 0)
            {
                msg = $"Success to add {images.Length} cover(s), now there are {images.Length + originCoverCount} covers in the mp3 file \"{mp3Path}\".";
            }
            else
            {
                msg = $"Success to add {images.Length} cover(s) to mp3 file \"{mp3Path}\".";
            }
            MessageBoxEx.Show(msg, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Example #30
0
        /// <summary>
        /// Creates a new music file
        /// </summary>
        /// <param name="file"></param>
        public MusicFile(string file)
        {
            // Store the file
            File = file;

            // The title is the file name
            Title = Path.GetFileNameWithoutExtension(file);

            try
            {
                // Mp3 file
                if (Path.GetExtension(file).ToLowerInvariant() == ".mp3")
                {
                    // Open the file
                    using (FileStream fileStream = new FileStream(File, FileMode.Open))
                    {
                        // Use the mp3 reader
                        using (var mp3Stream = new Mp3(fileStream, Mp3Permissions.Read))
                        {
                            // Has tags
                            if (mp3Stream.HasTags)
                            {
                                // Search in all tags
                                foreach (var tag in mp3Stream.GetAllTags())
                                {
                                    // Title
                                    if (tag.Title.IsAssigned)
                                    {
                                        Title = RemoveInvalidCharsAndTrim(tag.Title);
                                    }

                                    // Album
                                    if (tag.Album.IsAssigned)
                                    {
                                        Album = RemoveInvalidCharsAndTrim(tag.Album);
                                    }

                                    // Artist
                                    if (tag.Artists.IsAssigned)
                                    {
                                        Artists = RemoveInvalidCharsAndTrim(tag.Artists);
                                    }


                                    // We take the first tag with name we find
                                    if (tag.Title.IsAssigned)
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Could not read id3 tag from file: " + file);
                Console.WriteLine(ex.ToString());
            }



            // Build the title
            StringBuilder builder = new StringBuilder();

            // Title
            builder.Append(Title);

            // Album
            if (!string.IsNullOrEmpty(Album))
            {
                builder.AppendFormat(CultureInfo.InvariantCulture, " - {0}", Album);
            }

            // Artist
            if (!string.IsNullOrEmpty(Artists))
            {
                builder.AppendFormat(CultureInfo.InvariantCulture, " - {0}", Artists);
            }

            Name = builder.ToString();
        }