コード例 #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}");
                }
            }
        }
コード例 #2
0
 public void Save()
 {
     using (var mp3 = new Mp3(_file, Mp3Permissions.Write))
     {
         mp3.WriteTag(_tag, WriteConflictAction.NoAction);
     }
 }
コード例 #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);
            }
        }
コード例 #4
0
ファイル: DebuggingTests.cs プロジェクト: spottedmahn/Id3
        public void DebugTest()
        {
            var tag1 = new Id3Tag {
                Track = new TrackFrame(3, 10)
                {
                    Padding = 3
                },
            };

            _mp3.WriteTag(tag1, Id3Version.V23);

            Id3Tag tag2 = _mp3.GetTag(Id3Version.V23);

            tag2.Track.Padding = 4;
            Assert.Equal(Id3Version.V23, tag2.Version);
            Assert.Equal(Id3TagFamily.Version2X, tag2.Family);
            Assert.Equal("0003/0010", tag2.Track);
        }
コード例 #5
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();
        }
コード例 #6
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);
        }
コード例 #7
0
        private Task StartDownload()
        {
            return(Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    if (pendingTasks.Count == 0)
                    {
                        System.Threading.Thread.Sleep(1000);
                        continue;
                    }
                    string musicUrl = pendingTasks.Pop();
                    MusicTag musicTag = ParseMusicTag(musicUrl);
                    this.Dispatcher.Invoke(new Action <MusicTag>(DisplaySongInfo), musicTag);

                    string id = System.Web.HttpUtility.ParseQueryString(new Uri(musicUrl).Query)["id"];
                    WebRequest request = WebRequest.Create($"http://music.163.com/song/media/outer/url?id={id}.mp3");
                    request.Headers["User-Agent"] = UserAgent;
                    try
                    {
                        using (WebResponse webResponse = request.GetResponse())
                        {
                            if (webResponse.ContentType.IndexOf("text/html") >= 0)
                            {
                                this.Dispatcher.Invoke(new Action <string>(DisplayMessage), "未找到歌曲资源!");
                            }
                            else
                            {
                                this.Dispatcher.Invoke(new Action <long>(SetProgressBarMaximum), webResponse.ContentLength);
                                using (Stream responseStream = webResponse.GetResponseStream())
                                {
                                    using (FileStream fileStream = new FileStream(TempFile, FileMode.Create, FileAccess.Write))
                                    {
                                        byte[] buffer = new byte[10240];
                                        int length = 0;
                                        while ((length = responseStream.Read(buffer, 0, 10240)) > 0)
                                        {
                                            this.Dispatcher.BeginInvoke(new Action <long>(SetProgressBarValue), length);
                                            fileStream.Write(buffer, 0, length);
                                        }
                                    }
                                    string fileName = $"{musicTag.Author} - {musicTag.Title}.mp3";


                                    using (var mp3 = new Mp3(TempFile, Mp3Permissions.ReadWrite))
                                    {
                                        try
                                        {
                                            Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2X);
                                            if (tag == null)
                                            {
                                                tag = new Id3Tag();
                                            }
                                            tag.Title.EncodingType = Id3TextEncoding.Unicode;
                                            tag.Artists.EncodingType = Id3TextEncoding.Unicode;
                                            tag.Album.EncodingType = Id3TextEncoding.Unicode;
                                            tag.Title.Value = musicTag.Title;
                                            tag.Artists.Value.Clear();
                                            foreach (var item in musicTag.Author.Split(_authorSplitChars, StringSplitOptions.RemoveEmptyEntries))
                                            {
                                                tag.Artists.Value.Add(item.Trim());
                                            }
                                            tag.Album.Value = musicTag.Album;
                                            if (musicTag.AlbumImg != null)
                                            {
                                                PictureFrame pictureFrame = new PictureFrame();
                                                pictureFrame.PictureData = musicTag.AlbumImg;
                                                pictureFrame.PictureType = PictureType.FrontCover;
                                                tag.Pictures.Add(pictureFrame);
                                            }
                                            mp3.WriteTag(tag, Id3Version.V23, WriteConflictAction.Replace);
                                        }
                                        catch (Exception ex)
                                        {
                                            this.Dispatcher.Invoke(new Action <string>(DisplayMessage), ex.Message);
                                        }
                                    }

                                    fileName = fileName.Replace("\0", "");
                                    foreach (var item in System.IO.Path.GetInvalidFileNameChars())
                                    {
                                        fileName = fileName.Replace(item, '-');
                                    }
                                    string dir = System.IO.Path.Combine(DownloadFoler, musicTag.Author.Split(_authorSplitChars, StringSplitOptions.RemoveEmptyEntries)[0].Trim());
                                    if (!Directory.Exists(dir))
                                    {
                                        Directory.CreateDirectory(dir);
                                    }

                                    string target = System.IO.Path.Combine(dir, fileName);
                                    if (File.Exists(target))
                                    {
                                        File.Delete(target);
                                    }
                                    File.Move(TempFile, target);
                                    this.Dispatcher.Invoke(() =>
                                    {
                                        ProgressBar_Download.Value = 0;
                                    });
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        this.Dispatcher.Invoke(new Action(Reset));
                        this.Dispatcher.Invoke(new Action <string>(DisplayMessage), ex.Message);
                    }
                }
            }));
        }