问题
Is it possible to add custom tags (say "SongKey: Em") to an mp3 file using TagLib# libary?
回答1:
You can add custom tags to an MP3 by writing the data in custom (private) frames.
But First:
You must switch to ID3v2 if you are using ID3v1. Any version of ID3v2 will do, but the version compatible with most things is ID3v2.3.
The required using directives:
using System.Text;
using TagLib;
using TagLib.Id3v2;
Creating Private Frames:
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.
In the above code:
- Change
"<YourMP3.mp3>"
to the path to your MP3 file. - Change
"CustomKey"
to the name you want the key to be. - Change
"Sample Value"
to whatever data you want to store. - You can omit the last line if you have a custom method for saving.
Reading Private Frames:
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);
In the above code:
- Change
"<YourMP3.mp3>"
to the path to your MP3 file. - Change
"CustomKey"
to the name you want the key to be.
The difference between reading and writing is the third boolean parameter of the PrivateFrame.Get()
function. While reading, you pass false
and while writing you pass true
.
Additional Info:
Since byte[]
can be written on to the frames, not only text, but nearly any object type can be saved in the tags, provided you properly convert (and convert back when reading) the data.
For converting any object to a byte[]
, see this answer which uses a Binary Formatter
to do so.
来源:https://stackoverflow.com/questions/34507982/adding-custom-tag-using-taglib-sharp-library