使用tagLib sharp library添加自定义标签
答
您可以通过在自定义(专用)帧中写入数据来将自定义标签添加到MP3中。
但首先:
如果你正在使用的ID3v1您必须切换到ID3v2的。任何版本的ID3v2都可以,但版本兼容的东西是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()
函数的第三个布尔参数。在阅读时,你通过false
,同时写你通过true
。
附加信息:
由于byte[]
可以写入到帧,不仅是文字,但几乎任何对象类型可以保存在标签,只要你正确地转换(以及转换回时读取)数据。
若要将任何对象转换为byte[]
,请参阅this answer,它使用Binary Formatter
来执行此操作。