我有一个 mp3 文件,我想向其中添加专辑封面。艺术作品已保存到临时文件夹中,我已检查过它,它就在那里并且是 jpeg。
这是我给出的代码:
public void AddMp3Tags()
{
TagLib.File file = TagLib.File.Create(OutputPath + OutputName + "." + Format);
SetAlbumArt(Art, file);
file.Tag.Title = SongTitle;
file.Tag.Performers = Artists.Split(',');
file.Tag.Album = Album;
file.Tag.Track = (uint)TrackNumber;
file.Tag.Year = (uint)Convert.ToInt32(Regex.Match(Year, @"(\d)(\d)(\d)(\d)").Value);
file.Save();
}
public void SetAlbumArt(string url, TagLib.File file)
{
string path = string.Format(@"{0}temp\{1}.jpg", OutputPath, Guid.NewGuid().ToString());
using (WebClient client = new WebClient())
{
client.DownloadFile(new Uri(url), path);
}
TagLib.Picture pic = new TagLib.Picture
{
Type = TagLib.PictureType.FrontCover,
Description = "Cover",
MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg
};
MemoryStream ms = new MemoryStream();
Image image = Image.FromFile(path);
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
ms.Position = 0;
pic.Data = TagLib.ByteVector.FromStream(ms);
file.Tag.Pictures = new TagLib.IPicture[] { pic };
file.Save();
ms.Close();
}
除了仅显示黑框的艺术作品外,所有标签均已正确设置:Windows 媒体播放器中的黑盒封面艺术。 https://i.stack.imgur.com/IQ33p.png
我尝试了很多事情,我做错了什么?
所以我做了一些更多的研究,结果发现默认情况下 WMP 会尝试使用网络服务来获取专辑插图,我在 VLC 中打开这首歌并显示了插图。专辑代码已正确编写,如下所示:Mp3Tag 查看器/编辑器 https://i.stack.imgur.com/BbJdW.png
我发现的另一件事是我的标签使用 Id3v2.4 和 Id3v1。由于某种原因,WMP 不喜欢这样,所以我强迫 TagLib 使用 Id3v2.3。我还将文本编码更改为 UFT16,因为 UFT8 无法正常工作。专辑封面现在显示在 WMP 和 Windows 资源管理器中。
我还找到了一种不将图像写入磁盘的方法,即从网页下载数据并将其保存到内存中。
这是我的最终代码:
public void AddMp3Tags()
{
TagLib.Id3v2.Tag.DefaultVersion = 3;
TagLib.Id3v2.Tag.ForceDefaultVersion = true;
TagLib.File file = TagLib.File.Create(OutputPath + OutputName + ".mp3");
SetAlbumArt(Art, file);
file.Tag.Title = SongTitle;
file.Tag.Performers = Artists.Split(',');
file.Tag.Album = Album;
file.Tag.Track = (uint)TrackNumber;
file.Tag.Year = (uint)Convert.ToInt32(Regex.Match(Year, @"(\d)(\d)(\d)(\d)").Value);
file.RemoveTags(file.TagTypes & ~file.TagTypesOnDisk);
file.Save();
}
public void SetAlbumArt(string url, TagLib.File file)
{
string path = string.Format(@"{0}temp\{1}.jpg", OutputPath, Guid.NewGuid().ToString());
byte[] imageBytes;
using (WebClient client = new WebClient())
{
imageBytes = client.DownloadData(url);
}
TagLib.Id3v2.AttachedPictureFrame cover = new TagLib.Id3v2.AttachedPictureFrame
{
Type = TagLib.PictureType.FrontCover,
Description = "Cover",
MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg,
Data = imageBytes,
TextEncoding = TagLib.StringType.UTF16
};
file.Tag.Pictures = new TagLib.IPicture[] { cover };
}
我希望这可以帮助任何与我有同样问题的人,并且不需要像我一样花太多时间来解决这个问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)