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}"); } } }
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; }
/// <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); } } } }
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); } }
public Mp3Info(FileInfo fileInfo) { FileInfo = fileInfo; using (var mp3 = new Mp3(fileInfo.FullName)) { Tag = mp3.GetTag(Id3TagFamily.Version2X); } }
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 }
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); } }
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!"); }
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)); } }
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); }
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); }
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(); } }
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); } }
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(); } } }
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(); }
private ObservableCollection <Song> CreateListOfSongs(List <string> filesList) { ObservableCollection <Song> songs = new ObservableCollection <Song>(); foreach (var filePath in filesList) { using (var mp3 = new Mp3(filePath)) { Id3Tag tag = null; Id3Tag tag_1x = null; Id3Tag tag_2x = null; try { tag_1x = mp3.GetTag(Id3TagFamily.Version1X); } catch (Exception e) { Logging(e); } try { tag_2x = mp3.GetTag(Id3TagFamily.Version2X); } catch (Exception e) { Logging(e); } if (tag_2x != null) { tag = tag_2x; } else { tag = tag_1x; } if (string.IsNullOrEmpty(tag.Title)) { MessageBox.Show($"Трек {filePath} не содержит в себе название трека в MP3 TAG"); } else { var unixTime = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; //Чтение даты из времени создания файла в папке //var unixTime = (int)(File.GetCreationTimeUtc(filePath) - new DateTime(1970, 1, 1)).TotalSeconds; string artist; if (tag.Artists.Value.Count > 0 && tag.Artists.Value[0].Length < 50) { artist = tag.Artists.Value[0]; } else if (!string.IsNullOrEmpty(tag.Band.Value)) { artist = tag.Band.Value; } else { artist = ""; } Song newSong = new Song(artist, tag.Title, unixTime, filePath); if (ExistingSongs.Count(xx => xx.Title == newSong.Title & xx.Artist == newSong.Artist) > 0) { newSong.ExistEarlier = true; } songs.Add(newSong); } } } return(songs); }
public void AddTrack() { MLS_DB DB = new MLS_DB(); var ctx = MLS_DB.GetContext(); OpenFileDialog fileDialog = new OpenFileDialog(); fileDialog.InitialDirectory = @"C:\"; if (fileDialog.ShowDialog() == DialogResult.OK) { performer artist = new performer(); track curr_track = new track(); tracks_info tr_name = new tracks_info(); string server_path = @"C:\DexHydre\webserver\tracks"; string[] musicFiles = Directory.GetFiles(server_path, "*.mp3"); int new_number = musicFiles.Count() + 1; var musicFile = File.OpenRead(fileDialog.FileName); byte[] b = new byte[1024]; musicFile.Read(b, 0, b.Length); using (var mp3 = new Mp3(musicFile)) { Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2X); if (tag != null) { var duplicate_track = from tr in ctx.tracks_info join t in ctx.tracks on tr.track_id equals t.track_id join p in ctx.performers on t.performer_id equals p.performer_id where p.performer_name == tag.Artists && tr.track_name == tag.Title select tr.track_id; var existing_performer = from p in ctx.performers where p.performer_name == tag.Artists select p.performer_id; var new_track_id = (from t in ctx.tracks orderby t.track_id descending select t.track_id).Count() + 1; if (duplicate_track.Any()) { System.Windows.MessageBox.Show("Duplicate track"); } else { curr_track.track_id = new_track_id; if (existing_performer.Any()) { curr_track.performer_id = existing_performer.Single(); } else { artist.performer_name = tag.Artists; DB.performers.Add(artist); DB.SaveChanges(); curr_track.performer_id = existing_performer.Single(); } curr_track.track_duration = Convert.ToInt32(mp3.Audio.Duration.TotalSeconds); curr_track.bitrate = mp3.Audio.Bitrate; if (tag.Genre == null) { curr_track.genre = null; } else { curr_track.genre = tag.Genre; } tr_name.track_id = curr_track.track_id; tr_name.track_name = tag.Title; if (!musicFiles.Contains(curr_track.track_id.ToString())) { DB.tracks.Add(curr_track); DB.tracks_info.Add(tr_name); int dot_position = musicFile.Name.IndexOf("."); string new_name = server_path + @"\" + new_number.ToString() + musicFile.Name.Substring(dot_position); if (File.Exists(new_name)) { System.Windows.MessageBox.Show("Такой файл уже существует!"); } else { File.Copy(musicFile.Name, new_name); } DB.SaveChanges(); } } } else { System.Windows.MessageBox.Show("Invalid track data"); } } } }
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); }
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); } } })); }