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

最佳答案

您可以通过在自定义(专用)帧中写入数据来向MP3添加自定义标签。

但首先:

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

所需的using指令:

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进行转换。

关于c# - 使用tagLib Sharp库添加自定义标签,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34507982/

10-11 22:19
查看更多