使用 tagLib sharp 库添加自定义标签

adding custom tag using tagLib sharp library

是否可以使用 TagLib# 库将自定义标签(比如 "SongKey: Em")添加到 mp3 文件?

您可以通过在自定义(私有)框架中写入数据来将自定义标签添加到 MP3。

但首先:

如果您使用的是 ID3v1,则必须切换到 ID3v2。 ID3v2 的任何版本都可以,但与大多数 things 兼容的版本是 ID3v2.3.

需要使用的指令:

using System.Text;
using TagLib;
using TagLib.Id3v2;

正在创建私有框架:

File f = File.Create("<YourMP3.mp3>"); // Remember to change this...
TagLib.Id3v2.Tag t = (TagLib.Id3v2.Tag)f.GetTag(TagTypes.Id3v2); // You can add a true parameter to the GetTag function if the file doesn't already have a tag.
PrivateFrame p = PrivateFrame.Get(t, "CustomKey", true);
p.PrivateData = System.Text.Encoding.Unicode.GetBytes("Sample Value");
f.Save(); // This is optional.

在上面的代码中:

  • "<YourMP3.mp3>" 更改为您的 MP3 文件的路径。
  • "CustomKey" 更改为您想要的密钥名称。
  • "Sample Value" 更改为您要存储的任何数据。
  • 如果您有自定义保存方法,则可以省略最后一行。

读取私有帧:

File f = File.Create("<YourMP3.mp3>");
TagLib.Id3v2.Tag t = (TagLib.Id3v2.Tag)f.GetTag(TagTypes.Id3v2);
PrivateFrame p = PrivateFrame.Get(t, "CustomKey", false); // This is important. Note that the third parameter is false.
string data = Encoding.Unicode.GetString(p.PrivateData.Data);

在上面的代码中:

  • "<YourMP3.mp3>" 更改为您的 MP3 文件的路径。
  • "CustomKey" 更改为您想要的密钥名称。

读写的区别在于PrivateFrame.Get()函数的第三个boolean参数。阅读时,您通过了 false,而写作时,您通过了 true.

附加信息:

由于 byte[] 可以写在框架上,不仅是文本,而且几乎任何对象类型都可以保存在标签中,前提是您正确转换(并在阅读时转换回)数据。

要将任何对象转换为 byte[],请参阅使用 Binary Formatterthis answer