private static void TranscodeFile() { const string inputFile = @"c:\Users\Ben\Desktop\Bad Chemistry.flac"; const string outputFile = @"c:\Users\Ben\Desktop\Bad Chemistry.m4a"; const string errorsFile = @"c:\Users\Ben\Desktop\Bad Chemistry.log"; using (TagLib.File metadata = TagLib.File.Create(inputFile)) { TimeSpan duration = metadata.Properties.Duration; long inputFileSize = new FileInfo(inputFile).Length; // var converter = new DMCSCRIPTINGLib.Converter(); string encoder = "m4a FDK (AAC)"; // https://wiki.hydrogenaud.io/index.php?title=Fraunhofer_FDK_AAC#Usage_2 string compressionSettings = @"-cli_cmd=""-m 4 -p 2 --ignorelength -S -o {qt}[outfile]{qt} - """; Stopwatch stopwatch = Stopwatch.StartNew(); // converter.Convert(inputFile, outputFile, encoder, compressionSettings, errorsFile); stopwatch.Stop(); double relativeSpeed = duration.TotalMilliseconds / stopwatch.Elapsed.TotalMilliseconds; long outputFileSize = new FileInfo(outputFile).Length; Console.WriteLine( $"Converted {inputFile} to AAC-LC in {stopwatch.Elapsed.TotalSeconds:N} seconds\n{relativeSpeed:N}x speed\n{(double) outputFileSize / inputFileSize:P} file size\n{((double) inputFileSize - outputFileSize) / 1024 / 1024:N} MB saved"); string errorText = File.ReadAllText(errorsFile); if (string.IsNullOrWhiteSpace(errorText)) { errorText = "no errors"; } Console.WriteLine(errorText); File.Delete(errorsFile); } }
private static IEnumerable <string> ValidateTags(TagLib.File songTagFile) { if (string.IsNullOrEmpty(songTagFile.Tag.Title)) { yield return("Missing title"); } if (string.IsNullOrEmpty(songTagFile.Tag.Album)) { yield return("Missing album"); } if (string.IsNullOrEmpty(songTagFile.Tag.FirstPerformer)) { yield return("Missing performer"); } if (songTagFile.Properties.Duration.TotalSeconds < Constants.App.MIN_DURATION_IN_SECONDS) { yield return(string.Format("Duration must be greater than {0} seconds.", Constants.App.MIN_DURATION_IN_SECONDS)); } if (songTagFile.PossiblyCorrupt) { yield return(string.Format("File is possibly corrupt. Reasons: {0}", string.Join(", ", songTagFile.CorruptionReasons))); } }
private void SaveTags(TrackViewModel tracky) { int code = -1; try { foreach (var c in TagSavePending) { try { using (TagLib.File tlFile = TagLib.File.Create(c.Path)) { tlFile.Tag.Title = c.Title; tlFile.Tag.Album = c.Album; tlFile.Tag.Performers = new string[] { c.Artist }; tlFile.Tag.Genres = new[] { c.Genre }; tlFile.Save(); } TagSavePending.Remove(c); } catch (Exception e) { Console.WriteLine(e); } } } catch (Exception ex) { } }
private void coverbildAusAPETagsExtrahierenToolStripMenuItem_Click(object sender, EventArgs e) { if (openFlac.ShowDialog(this) != DialogResult.OK) { return; } TagLib.File file = TagLib.File.Create(openFlac.FileName); IPicture[] pictures = file.Tag.Pictures; byte[] data = pictures[0].Data.Data; Data = data; file.Dispose(); }
public Song(string f) { //TagLib.File file = new AudioFile(f); TagLib.File file = TagLib.File.Create(f); var tag = file.Tag; Artist = String.IsNullOrWhiteSpace(tag.FirstAlbumArtist) ? tag.FirstArtist : tag.FirstAlbumArtist; Album = tag.Album; Genre = tag.FirstGenre; Title = tag.Title; Track = tag.Track; File = f; Size = new FileInfo(f).Length / 1024 / 1024; }
public Task <int> GetBitrate(string filePath) { return(Task.Run(() => { try { using (TagLib.File metadata = TagLib.File.Create(filePath)) { return metadata.Properties.AudioBitrate; } } catch (Exception e) when(e is UnsupportedFormatException || e is CorruptFileException) { LOGGER.Error("Encountered unreadable file while trying to get bitrate: {0} ({1})", e.Message, filePath); throw; } })); }
public static async Task ExecuteAsync(Arguments arguments) { string databasePath; await LoginIfNeedAsync(arguments); databasePath = Path.Combine(arguments.Directory, ".nlyric"); LoadDatabase(databasePath); foreach (string audioPath in Directory.EnumerateFiles(arguments.Directory, "*", SearchOption.AllDirectories)) { string lrcPath; lrcPath = Path.ChangeExtension(audioPath, ".lrc"); if (CanSkip(audioPath, lrcPath)) { continue; } using (TagLib.File audioFile = TagLib.File.Create(audioPath)) { Tag tag; TrackInfo trackInfo; Logger.Instance.LogInfo($"开始搜索文件\"{Path.GetFileName(audioPath)}\"的歌词。"); tag = audioFile.Tag; trackInfo = await SearchTrackAsync(tag); if (trackInfo is null) { Logger.Instance.LogWarning($"无法找到文件\"{Path.GetFileName(audioPath)}\"的网易云音乐ID!"); } else { Logger.Instance.LogInfo($"已获取文件\"{Path.GetFileName(audioPath)}\"的网易云音乐ID: {trackInfo.Id}。"); await TryDownloadLyricAsync(trackInfo, lrcPath); } } SaveDatabaseCore(databasePath); Logger.Instance.LogNewLine(); Logger.Instance.LogNewLine(); } SaveDatabase(databasePath); }
public void MusicTags(int num, int session) { PassArguments result = songArray[session][num]; try { //===edit tags==== TagLib.File f = TagLib.File.Create(_dir + EscapeFilename(result.PassedFileName) + ".mp3"); f.Tag.Clear(); f.Tag.AlbumArtists = new string[1] { result.PassedArtist }; f.Tag.Performers = new string[1] { result.PassedArtist }; f.Tag.Title = result.PassedSong; f.Tag.Album = result.PassedAlbum; // // Log(result.passedFileName + " and " + result.passedAlbumID); Image currentImage = GetAlbumArt(num, session); Picture pic = new Picture(); pic.Type = PictureType.FrontCover; pic.MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg; pic.Description = "Cover"; MemoryStream ms = new MemoryStream(); currentImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); // <-- Error doesn't occur anymore ms.Position = 0; pic.Data = ByteVector.FromStream(ms); f.Tag.Pictures = new IPicture[1] { pic }; f.Save(); ms.Close(); } catch (Exception ex) { Log("[Error: x7] " + ex.Message + Environment.NewLine + Environment.NewLine + result.PassedFileName, true); } }
private bool WriteMp3Metadata() { using (TagLib.File file = TagLib.File.Create(_filepath, "taglib/mp3", ReadStyle.Average)) { var tags = (Tag)file.GetTag(TagTypes.Id3v2); if (_coverBytes.Length > 0) { var byteVector = new ByteVector(_coverBytes); var coverPicture = new Picture { Description = "Cover", Data = byteVector, MimeType = MediaTypeNames.Image.Jpeg, Type = PictureType.FrontCover }; var attachedPictureFrame = new AttachedPictureFrame(coverPicture); tags.Pictures = new IPicture[] { attachedPictureFrame }; } tags.AddFrame(MetadataHelpers.BuildTextInformationFrame("TMED", "Digital Media")); if (_trackInfo?.TrackTags != null) { tags.Title = _trackInfo.TrackTags.Title; tags.Performers = _trackInfo.TrackTags.Artists.Select(x => x.Name).ToArray(); tags.AlbumArtists = _albumInfo.AlbumTags.Artists.Select(x => x.Name).ToArray(); // i don't like just using ART_NAME as the only album artist tags.Composers = _trackInfo.TrackTags.Contributors.Composers; if (_trackInfo.TrackTags.TrackNumber != null) { tags.Track = uint.Parse(_trackInfo.TrackTags.TrackNumber); } if (_trackInfo.TrackTags.DiscNumber != null) { tags.Disc = uint.Parse(_trackInfo.TrackTags.DiscNumber); } if (_trackInfo.TrackTags.Bpm != null) { string bpm = _trackInfo.TrackTags.Bpm; if (double.TryParse(bpm, out double bpmParsed)) { bpmParsed = Math.Round(bpmParsed); bpm = bpmParsed.ToString(CultureInfo.InvariantCulture); } tags.BeatsPerMinute = uint.Parse(bpm); } tags.AddFrame(MetadataHelpers.BuildTextInformationFrame("TSRC", _trackInfo.TrackTags.Isrc)); tags.AddFrame(MetadataHelpers.BuildTextInformationFrame("TPUB", _trackInfo.TrackTags.Contributors.Publishers)); tags.AddFrame(MetadataHelpers.BuildTextInformationFrame("TLEN", _trackInfo.TrackTags.Length)); tags.AddFrame(MetadataHelpers.BuildUserTextInformationFrame("EXPLICIT", _trackInfo.TrackTags.ExplicitLyrics)); tags.AddFrame(MetadataHelpers.BuildUserTextInformationFrame("REPLAYGAIN_TRACK_GAIN", _trackInfo.TrackTags.Gain)); tags.AddFrame(MetadataHelpers.BuildUserTextInformationFrame("WRITERS", _trackInfo.TrackTags.Contributors.Writers)); tags.AddFrame(MetadataHelpers.BuildUserTextInformationFrame("AUTHORS", _trackInfo.TrackTags.Contributors.Authors)); tags.AddFrame(MetadataHelpers.BuildUserTextInformationFrame("TIPL", "PRODUCERS", _trackInfo.TrackTags.Contributors.Publishers)); tags.AddFrame(MetadataHelpers.BuildUserTextInformationFrame("TIPL", "ENGINEERS", _trackInfo.TrackTags.Contributors.Engineers)); tags.AddFrame(MetadataHelpers.BuildUserTextInformationFrame("TIPL", "MIXERS", _trackInfo.TrackTags.Contributors.Mixers)); } if (_albumInfo?.AlbumTags != null) { tags.Album = _albumInfo.AlbumTags.Title; tags.Genres = _albumInfo.AlbumTags.Genres.GenreData.Select(x => x.Name).ToArray(); if (_albumInfo.AlbumTags.NumberOfTracks != null) { tags.TrackCount = uint.Parse(_albumInfo.AlbumTags.NumberOfTracks); } if (_albumInfo.AlbumTags.NumberOfDiscs != null) { tags.DiscCount = uint.Parse(_albumInfo.AlbumTags.NumberOfDiscs); } if (_albumInfo.AlbumTags.Type == "Compilation" || _albumInfo.AlbumTags.Type == "Playlist") { tags.IsCompilation = true; } tags.Copyright = _albumInfo.AlbumTags.Copyright; string year = _albumInfo.AlbumTags.ReleaseDate; if (!string.IsNullOrWhiteSpace(year)) { string[] yearSplit = year.Split("-"); if (yearSplit[0].Length == 4 && uint.TryParse(yearSplit[0], out uint yearParsed)) { tags.Year = yearParsed; } } tags.AddFrame(MetadataHelpers.BuildTextInformationFrame("TPUB", _albumInfo.AlbumTags.Label)); tags.AddFrame(MetadataHelpers.BuildTextInformationFrame("TDOR", _albumInfo.AlbumTags.ReleaseDate)); tags.AddFrame(MetadataHelpers.BuildUserTextInformationFrame("UPC", _albumInfo.AlbumTags.Upc)); } if (_trackInfo?.Lyrics != null) { tags.Lyrics = _trackInfo.Lyrics.UnSyncedLyrics; WriteLyricsFile(); } try { file.Save(); } catch (IOException ex) { Console.WriteLine(ex.Message); return(false); } } return(true); }
private static DateTime?ParsePhotoDate(string path) { TagLib.File file = null; //Get CR2 EXIF date if (Path.GetExtension(path) == ".CR2") { return(GetRC2PhotoDate(path)); } try { file = TagLib.File.Create(path); } catch (UnsupportedFormatException) { Print("UNSUPPORTED FILE not moving: " + path); return(null); } catch (CorruptFileException) { var time = LastWriteTime(path); Console.WriteLine("---------------"); Print("Corrupted File, using last Write time " + path + time); LogUtility.WriteToLog("Corrupted File, using last Write time " + path + time, LogUtility.Level.Error); Console.WriteLine("---------------"); return(LastWriteTime(path)); } var image = file as TagLib.Image.File; if (image == null) { Print("NOT AN IMAGE FILE Using file date: " + path); return(LastWriteTime(path)); } return(image.ImageTag.DateTime ?? LastWriteTime(path)); //Console.WriteLine(String.Empty); //Console.WriteLine(path); //Console.WriteLine(String.Empty); //Console.WriteLine("Tags in object : " + image.TagTypes); //Console.WriteLine(String.Empty); //Console.WriteLine("Comment : " + image.ImageTag.Comment); //Console.Write("Keywords : "); //foreach (var keyword in image.ImageTag.Keywords) //{ // Console.Write(keyword + " "); //} //Console.WriteLine(); //Console.WriteLine("Rating : " + image.ImageTag.Rating); //Console.WriteLine("DateTime : " + image.ImageTag.DateTime); //Console.WriteLine("Orientation : " + image.ImageTag.Orientation); //Console.WriteLine("Software : " + image.ImageTag.Software); //Console.WriteLine("ExposureTime : " + image.ImageTag.ExposureTime); //Console.WriteLine("FNumber : " + image.ImageTag.FNumber); //Console.WriteLine("ISOSpeedRatings : " + image.ImageTag.ISOSpeedRatings); //Console.WriteLine("FocalLength : " + image.ImageTag.FocalLength); //Console.WriteLine("FocalLength35mm : " + image.ImageTag.FocalLengthIn35mmFilm); //Console.WriteLine("Make : " + image.ImageTag.Make); //Console.WriteLine("Model : " + image.ImageTag.Model); //if (image.Properties != null) //{ // Console.WriteLine("Width : " + image.Properties.PhotoWidth); // Console.WriteLine("Height : " + image.Properties.PhotoHeight); // Console.WriteLine("Type : " + image.Properties.Description); //} //Console.WriteLine(); //Console.WriteLine("Writable? : " + image.Writeable.ToString()); //Console.WriteLine("Corrupt? : " + image.PossiblyCorrupt.ToString()); //if (image.PossiblyCorrupt) //{ // foreach (string reason in image.CorruptionReasons) // { // Console.WriteLine(" * " + reason); // } //} //Console.WriteLine("---------------------------------------"); }
private async Task <bool> GenerateM3U(string folderpath) { if (string.IsNullOrEmpty(folderpath) || !Directory.Exists(folderpath)) { ResetFiles(); return(false); } TxtDirectory.Text = folderpath.Trim(); var files = Mp3Files.SelectedItems; bool isChkAfterPatternChecked = ChkAfterPattern.IsChecked != null && ChkAfterPattern.IsChecked.Value; string pattern = TxtPattern.Text; bool forceId3Tagging = ChkForceId3Tagging.IsChecked != null && ChkForceId3Tagging.IsChecked.Value; return(await Task.Run(delegate { string cnt = "#EXTM3U\r\n"; foreach (var file in files) { var item = file as FileItem; if (item == null) { continue; } long duration = GetDuration(item.Filename); string filename = Path.GetFileNameWithoutExtension(item.Filename); if (string.IsNullOrEmpty(filename)) { filename = Path.GetFileName(item.Filename); } if (string.IsNullOrEmpty(filename)) { continue; } int p = filename.IndexOf(pattern, StringComparison.OrdinalIgnoreCase); if (isChkAfterPatternChecked) { p += pattern.Length; } string artist; string title; if (p != -1) { artist = filename.Substring(0, p).Trim(); title = Path.GetFileNameWithoutExtension(filename.Substring(p + 1).Trim()); } else { artist = filename; title = Path.GetFileNameWithoutExtension(filename); } if (!item.HasId3Tag || forceId3Tagging) { using (TagLib.File f = TagLib.File.Create(item.Filename)) { f.Tag.Title = title; f.Tag.Composers = new [] { artist }; f.Tag.AlbumArtists = new[] { artist }; f.Tag.Performers = new [] { artist }; f.Save(); } } cnt += string.Format("#EXTINF:{0},{1} - {2}\r\n", duration, artist, title); cnt += Path.GetFileName(item.Filename) + "\r\n"; var cnt1 = cnt; _ctx.Post(o => { if (!string.IsNullOrEmpty(cnt1)) { TxtInfo.Text = cnt1; } }, null); } _ctx.Post(o => { TxtInfo.Text = cnt; }, null); string name = Path.GetFileNameWithoutExtension(folderpath); string targetFilename = Path.Combine(folderpath, name + ".m3u"); File.WriteAllText(targetFilename, cnt, Encoding.UTF8); if (File.Exists(targetFilename)) { targetFilename.ShowExplorer(); } else { return false; } return true; })); }
private void LoadFiles(string folderpath) { List <TagTypes> tags = new List <TagTypes>() { TagTypes.Ape, TagTypes.Apple, TagTypes.Asf, TagTypes.AudibleMetadata, TagTypes.DivX, TagTypes.FlacMetadata, TagTypes.GifComment, TagTypes.IPTCIIM, TagTypes.Id3v1, TagTypes.Id3v2, TagTypes.JpegComment, TagTypes.MovieId, TagTypes.Png, TagTypes.RiffInfo, TagTypes.TiffIFD, TagTypes.XMP, TagTypes.Xiph }; List <string> additionalTags = new List <string>() { "album", "artists", "comment", "lyrics", "composers", "disc", "disccount", "genres", "performers", "title", "trackcount", "year" }; Mp3Files.SelectionMode = SelectionMode.Multiple; Mp3Files.Items.Clear(); var files = GetFilesInFolder(folderpath); foreach (var file in files) { using (TagLib.File f = TagLib.File.Create(file)) { string name = Path.GetFileName(file); Trace.WriteLine("Some info: " + name); foreach (var tag in tags) { try { var info = f.GetTag(tag); if (info != null) { Trace.WriteLine(" " + tag + ": " + info); } } catch { // ignore } } foreach (var tagname in additionalTags) { try { ShowTag(f, tagname); } catch { // ignore } } //string tagPerfomer = string.Join(",", f.Tag.PerformersSort); string tagAlbum = f.Tag.Album; string tagTitle = f.Tag.Title; bool hasId3Tag = !string.IsNullOrEmpty(tagAlbum) || !string.IsNullOrEmpty(tagTitle); string additionalInformation = string.Format("{0} - {1}", string.IsNullOrEmpty(tagAlbum) ? "x" : tagAlbum, string.IsNullOrEmpty(tagTitle) ? "x" : tagTitle ); var item = new FileItem() { Name = string.Format("{0} ({1})", name, additionalInformation), Filename = file, HasId3Tag = hasId3Tag }; Mp3Files.Items.Add(item); } } Mp3Files.SelectAll(); }
private void ShowTag(TagLib.File file, string key) { if (file == null) { return; } try { switch (key) { case "album": Dump(key, file.Tag.Album); break; case "artists": Dump(key, ArrayToString(file.Tag.AlbumArtists)); break; case "comment": Dump(key, file.Tag.Comment); break; case "lyrics": Dump(key, file.Tag.Lyrics); break; case "composers": Dump(key, ArrayToString(file.Tag.Composers)); break; case "disc": Dump(key, file.Tag.Disc); break; case "disccount": Dump(key, file.Tag.DiscCount); break; case "genres": Dump(key, ArrayToString(file.Tag.Genres)); break; case "performers": Dump(key, ArrayToString(file.Tag.Performers)); break; case "title": Dump(key, file.Tag.Title); break; case "track": Dump(key, file.Tag.Track); break; case "trackcount": Dump(key, file.Tag.TrackCount); break; case "year": Dump(key, file.Tag.Year); break; } } catch { // ignore } }
public void OnFoundFile(List <string> relativePath, string path) { TagLib.File metaData = null; try { metaData = TagLib.File.Create(path); } catch (Exception e) { return; } var track = _workingTracks.FirstOrDefault(t => t.Path == path) ?? _tracks.FirstOrDefault(t => t.Path == path); if (track == null) { track = new Track { Name = !metaData.Tag.IsEmpty && !string.IsNullOrEmpty(metaData.Tag.Title) ? metaData.Tag.Title : Path.GetFileNameWithoutExtension(path), Path = path, RelativePath = relativePath, Duration = metaData.Properties.Duration, }; _workingTracks.Add(track); } var hasSubtitle = false; foreach (var codec in metaData.Properties.Codecs.OfType <SubtitleTrack>()) { hasSubtitle = true; } if (!hasSubtitle || track.Subtitles.Any(subtitle => subtitle.Name == "encoded subtitles")) { return; } if (!Directory.Exists(Locations.DataFolder + "/subtitles")) { Directory.CreateDirectory(Locations.DataFolder + "/subtitles"); } var subtitleLocation = Locations.DataFolder + "/subtitles/inner_subtitle" + LastSubtitleTag + ".srt"; var _process = new Process { StartInfo = new ProcessStartInfo { FileName = @"ffmpeg", Arguments = "-i \"" + track.Path + "\" -y -an -vn -threads 1 -c:s:0 srt \"" + subtitleLocation + "\"", UseShellExecute = false, CreateNoWindow = true, }, }; LastSubtitleTag += 1; _process.Exited += (sender, args) => { track.Subtitles.Add(new Subtitle { Name = "encoded subtitles", Path = subtitleLocation }); Save(); }; _process.EnableRaisingEvents = true; _process.Start(); }
public static void ExportRelease(DiscogsRelease release, string folder) { if (release.videos == null) { return; } foreach (DiscogsVideo releaseVideo in release.videos) { if (!GetAudioFilePath(releaseVideo.uri, out string src)) { continue; } string filename = getEscaped(releaseVideo.title); string releaseName = $"{string.Join(", ", release.artists?.Select(a => a.name).ToArray() ?? new string[0])} - {release.title}"; foreach (char invalidPathChar in Path.GetInvalidPathChars()) { releaseName = releaseName.Replace(invalidPathChar, ' '); } string destFolder = Path.Combine(folder, releaseName); if (!Directory.Exists(destFolder)) { Directory.CreateDirectory(destFolder); } string dest = Path.Combine(destFolder, $"{filename}{AudioExtension}"); if (!File.Exists(src) || File.Exists(dest)) { continue; } try { File.Copy(src, dest); TagLib.File file = TagLib.File.Create(dest); DiscogsTrack track = getTrack(releaseVideo, release); file.Tag.Title = track?.title; file.Tag.Performers = track?.artists?.Select(a => a.name).ToArray() ?? release.artists?.Select(a => a.name).ToArray() ?? new string[0]; file.Tag.Album = release.title; file.Tag.AlbumArtists = release.artists?.Select(a => a.name).ToArray() ?? new string[0]; file.Tag.Genres = release.genres; try { IPicture cover = new Picture(GetImageFilePath(release.images?[0])); file.Tag.Pictures = new[] { cover }; } catch (Exception e) { Console.WriteLine($@"tagging {release.title}{e}"); } file.Save(); } catch (Exception e) { Console.WriteLine($@"{src} --> {dest} {e}"); } } }