Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
657 views
in Technique[技术] by (71.8m points)

c# - adding custom tag using tagLib sharp library

Is it possible to add custom tags (say "SongKey: Em") to an mp3 file using TagLib# libary?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...