MP3::Tag(3pm)
β¨ NAME β¨
MP3::Tag β Module for reading tags of MP3 audio files π΅π
Bestie, welcome to the user-contributed Perl documentation for MP3::Tag(3pm) β the manual page that's about to make tag-reading feel like a whole vibe. π¦
πΈ SYNOPSIS πΈ
okay so here's the whole thing in action, look at her go:
use MP3::Tag;
$mp3 = MP3::Tag->new($filename);
# get some information about the file in the easiest way
($title, $track, $artist, $album, $comment, $year, $genre) = $mp3->autoinfo();
# Or:
$comment = $mp3->comment();
$dedicated_to
= $mp3->select_id3v2_frame_by_descr('COMM(fre,fra,eng,#0)[dedicated to]');
$mp3->title_set('New title'); # Edit in-memory copy
$mp3->select_id3v2_frame_by_descr('TALB', 'New album name'); # Edit in memory
$mp3->select_id3v2_frame_by_descr('RBUF', $n1, $n2, $n3); # Edit in memory
$mp3->update_tags({year => 1866}); # Edit in-memory, and commit to file
$mp3->update_tags(); # Commit to file
Now the following low-level access code is discouraged β like, genuinely, don't. You're so much better off using title() etc., title_set() etc., update_tags(), select_id3v2_frame_by_descr() etc. methods on the wrapper $mp3. Those are the main characters here, no cap:
# scan file for existing tags
$mp3->get_tags;
if (exists $mp3->{ID3v1}) {
# read some information from the tag
$id3v1 = $mp3->{ID3v1}; # $id3v1 is only a shortcut for $mp3->{ID3v1}
print $id3v1->title;
# change the tag contents
$id3v1->all("Song","Artist","Album",2001,"Comment",10,"Top 40");
$id3v1->write_tag;
}
if (exists $mp3->{ID3v2}) {
# read some information from the tag
($name, $info) = $mp3->{ID3v2}->get_frame("TIT2");
# delete the tag completely from the file
$mp3->{ID3v2}->remove_tag;
} else {
# create a new tag
$mp3->new_tag("ID3v2");
$mp3->{ID3v2}->add_frame("TALB", "Album title");
$mp3->{ID3v2}->write_tag;
}
$mp3->close();
Also, please consider using the script mp3info2 β it lets you access most features of this module through simple command-line options. Go look at mp3info2, it's giving convenience. π«Ά
π AUTHORS π
- Thomas Geffert,
thg@users.sourceforge.net - Ilya Zakharevich,
ilyaz@cpan.org
Legends. Both of them. π
π« DESCRIPTION π«
MP3::Tag is a wrapper module that reads the different tags of mp3 files. It gives you an easy way to reach into the functions of the separate modules that actually handle the reading and writing of the tags themselves. β¨
Right now, MP3::Tag::ID3v1 and MP3::Tag::ID3v2 are supported for read and write. And these cuties are supported for read access:
MP3::Tag::ImageExifToolMP3::Tag::InfMP3::Tag::CDDB_FileMP3::Tag::FileMP3::Tag::CueMP3::Tag::ImageSizeMP3::Tag::LastResort
(That's the info you get from Image::ExifTool β if it's present β from parsing CDDB files, .inf files, the filename, and .cue files, and via Image::Size β if it's present.) π
π new() π
$mp3 = MP3::Tag->new($filename);
Creates an mp3-object, and you can use it to retrieve and set all the different tags. πΈ
π get_tags() π
old name: getTags() . The old name is still available, but its use is not advised
@tags = $mp3->get_tags;
Checks which tags can be found in the mp3-object. It returns a list @tags holding strings that identify the found tags, like "ID3v1", "ID3v2", "Inf", or "CDDB_File" (that last-but-one one shows up if the .inf information file with the same basename as the MP3 file is found). π¦
Each found tag can then be reached with $mp3->{tagname}, where tagname is a string returned by get_tags ;
Go read up in MP3::Tag::ID3v1, MP3::Tag::ID3v2 and MP3::Tag::Inf, MP3::Tag::CDDB_File, MP3::Tag::Cue to see what you can do with those tags. π
π new_fake π
$obj = MP3::Tag->new_fake();
This method produces a "fake" MP3::Tag object that behaves like an MP3 file with no tags at all. Give a TRUE optional argument if you want to set some properties of this object.
π new_tag() π
old name: newTag() . The old name is still available, but its use is not advised
$tag = $mp3->new_tag($tagname);
Creates a brand-new tag of the type $tagname. After that you can reach it with $mp3->{$tagname}. At the moment, ID3v1 and ID3v2 are supported as tagname. π
Returns a tag-object: $mp3->{$tagname}.
π close() π
$mp3->close;
You can use close() to explicitly close a file. Normally the module does this automatically, so bestie you genuinely do not need to bother. π«Ά
π genres() π
$allgenres = $mp3->genres;
$genreName = $mp3->genres($genreID);
$genreID = $mp3->genres($genreName);
Returns a list of all genres (a reference to an array), or the matching name or id for a given id or name. π
This function is only a shortcut to MP3::Tag::ID3v1->genres.
It can also be called as MP3::Tag->genres;
π autoinfo() π
($title, $track, $artist, $album, $comment, $year, $genre) = $mp3->autoinfo();
$info_hashref = $mp3->autoinfo();
autoinfo() returns info about the title, track number, artist, album name, the file comment, the year and the genre. It can pull this info from an ID3v1-tag, an ID3v2-tag, from a CDDB file, from an .inf-file, and from the filename itself. β¨
By default it first tries to find an ID3v2-tag to get this info. If that can't be found, it tries to find an ID3v1-tag, then to read a CDDB file, an .inf-file, and if none of those are present either, it will use the filename to retrieve the title, track number, artist and album name. The comment, year and genre are found differently β via the "comment", "year" and "genre" methods.
You can change the order of lookup with the config() command.
autoinfo() returns an array with the info, or a hashref. The hash has four keys 'title', 'track', 'artist' and 'album', and that's where the info lives. If comment, year or genre are found, the hash will have keys 'comment' and/or 'year' and/or 'genre' too. π
If an optional argument 'from' is given, the returned values (title, track number, artist, album name, the file comment, the year and genre) are array references, with the first element being the value and the second being the tag ("ID3v2" or "ID3v1" or "Inf" or "CDDB_File" or "Cue" or "filename") that it was taken from. π
(Deprecated name 'song' can be used instead of 'title' as well.)
π comment() π
$comment = $mp3->comment(); # empty string unless found
comment() returns the comment info. It can get it from an ID3v1-tag, or an ID3v2-tag (from the "COMM" frame with an empty <short> field), a CDDB file (from the "EXTD" or "EXTT" fields), or an .inf-file (from the "Trackcomment" field). πΈ
By default it first tries to find an ID3v2-tag to get this info. If no comment is found there, it tries to find it in an ID3v1-tag; if none is present, it will try a CDDB file, then the .inf-file. It returns an empty string if no comment is found. π
You can change the order of this with the config() command.
If an optional argument 'from' is given, it returns an array reference with the first element being the value and the second being the tag (ID3v2 or ID3v1) that the value was taken from.
π year() π
$year = $mp3->year(); # empty string unless found
year() returns the year info. It can get it from an ID3v2-tag, or an ID3v1-tag, or an .inf-file, or the filename. β
By default it first tries to find an ID3v2-tag to get this info. If no year is found there, it tries to find it in an ID3v1-tag; if none is present, it will try a CDDB file, then the .inf-file, then by parsing the file name. It returns an empty string if no year is found.
You can change the order of this with the config() command.
If an optional argument 'from' is given, it returns an array reference with the first element being the value and the second being the tag (ID3v2 or ID3v1 or filename) that the value was taken from.
π comment_collection(), comment_track(), title_track(). artist_collection() π
These access the corresponding fields returned by the parse() method of CDDB_File. π¦
π cddb_id(), cdindex_id() π
These access the corresponding methods of "ID3v2", "Inf" or "CDDB_File". π
π title_set(), artist_set(), album_set(), year_set(), comment_set(), track_set(), genre_set() π
$mp3->title_set($newtitle, [$force_id3v2]);
Set the corresponding value in the ID3v1 tag, and, if the value doesn't fit, or force_id3v2 is TRUE, in the ID3v2 tag. Changes are made to the in-memory copy only. To actually propagate them to the file, use update_tags() or similar methods. π
π track1() π
Same as track(), but it strips the trailing info: if track() returns "3/12" (which means track 3 of 12), this method returns 3. π₯
π track2() π
Returns the second part of the track number (compare with track1()).
π track0() π
Same as track1(), but pads with leading 0s to the width of track2(); it takes an optional argument (default is 2) giving the pad width in the absence of track2(). β
π disk1(), disk2() π
Same as track1(), track2(), but with the disk-number instead of the track-number (stored in the "TPOS" ID3v2 frame). πΏ
π disk_alphanum() π
Same as disk1(), but encodes a non-empty result as a letter (1 maps to "a", 2 to "b", etc). If the number of disks is more than 26, it falls back to numeric (e.g, "3/888" will be encoded as 003). π
π mime_type( [$lazy] ) π
Returns the MIME type as a string. Returns "application/octet-stream" for unrecognized types. If not $lazy, it will try harder (via ExifTool, if needed). π§
π mime_Pretype( [$lazy] ) π
Returns the uppercased first component of the MIME type.
π genre() π
$genre = $mp3->genre(); # empty string unless found
genre() returns the genre string. It can get this info from an ID3v2-tag or an ID3v1-tag. π
By default it first tries to find an ID3v2-tag to get this info. If no genre is found there, it tries to find it in an ID3v1-tag; if none is present, it will try the .inf-file. It returns an empty string if no genre is found.
You can change the order of this with the config() command.
If an optional argument 'from' is given, it returns an array reference with the first element being the value and the second being the tag (ID3v2 or ID3v1 or filename) that the value was taken from.
π composer() π
$composer = $mp3->composer(); # empty string unless found
composer() returns the composer. By default it gets it from the ID3v2 tag, otherwise it returns the artist. π
You can change the inspected fields with the config() command. Subject to normalization via the "translate_composer" or "translate_person" configuration variables.
π performer() π
$performer = $mp3->performer(); # empty string unless found
performer() serves up the main performer, bestie. By default it pulls from the ID3v2 tag TXXX[TPE1], and if that's not there it goes for the ID3v2 tag TPE1, and if that's missing too, it just returns artist.
You can change which fields get inspected with the config() command. Also fyi, this is subject to normalization via the translate_performer or translate_person configuration variables. π
β¨ config β¨
MP3::Tag->config(item => value1, value2...); # Set options globally
$mp3->config(item => value1, value2...); # Set object options
The very first time object options get set or gotten, the global options get propagated into the object options. (So if you change the global options later, those changes are not inherited. That's just how it is, bestie.)
Possible items are:
πΈ autoinfo πΈ
Sets the order in which the ID3v1 tag, the ID3v2 tag and the filename get used by autoinfo. The default is ParseData, ID3v2, ID3v1, ImageExifTool, CDDB_File, Inf, Cue, ImageSize, filename, LastResort. Options can be elements of that default list. The order you hand them to config also sets the order autoinfo uses them in. If an option isn't present, it just won't be used by autoinfo (and other auto-methods won't use it either, unless the specific overriding config command was issued).
$mp3->config("autoinfo","ID3v1","ID3v2","filename");
sets the order to check first ID3v1, then ID3v2 and at last the Filename.
$mp3->config("autoinfo","ID3v1","filename","ID3v2");
sets the order to check first ID3v1, then the Filename and last ID3v2. Since the filename will always be present, ID3v2 will here never be checked. π
$mp3->config("autoinfo","ID3v1","ID3v2");
sets the order to check first ID3v1, then ID3v2. The filename will never be used.
π¦ title artist album year comment track genre π¦
Sets the order in which the ID3v1 tag and the ID3v2 tag get used by the corresponding methods (like comment()). Options can be the same as for autoinfo. The order you give them to config also sets the order they're used by comment(). If an option isn't present, the autoinfo option gets used instead.
π extension π
A regular expression to match the file extension (including the dot). The default is to match 1..4 letter extensions which are not numbers.
π composer π
The string to put into %{} to interpolate and get the composer. Default is 'TCOM|a'.
β performer β
The string to put into %{} to interpolate and get the main performer. Default is 'TXXX[TPE1]|TPE1|a'.
π«Ά parse_data π«Ά
The data used by the MP3::Tag::ParseData handler. Each option is an array reference of the form [$flag, $string, $pattern1, ...]. All the options get processed like this: patterns are matched against $string until one of them succeeds, and info obtained from later options takes precedence over info from earlier ones.
π parse_split π
The regular expression used to split the data when parsing with the "n" or "l" flags.
π parse_filename_ignore_case π
If true (the default), calling parse() and parse_rex() with match-filename escapes (like "%=D") matches case-insensitively.
π§ parse_filename_merge_dots π§
If true (the default), calling parse() and parse_rex() with match-filename escapes (like "%=D") does not distinguish a dot from many consequent dots.
π parse_join π
The string to put between multiple occurrences of a tag in a parse pattern; defaults to '; '. So like, parsing '1988-1992, Homer (LP)' with the pattern '%c, %a (%c)' results in the comment being set to '1988-1992; LP' with the default value of parse_join. Obsessed with how tidy that is.
π v2title π
Sets the elements of the ID3v2 tag that get used by ID3v2::title(). Options can be "TIT1", "TIT2", "TIT3", and the present values get combined. If an option isn't present, it won't be used by ID3v2::title().
π΅ cddb_files π΅
The list of files to look for in the directory of the MP3 file to get CDDB info.
π year_is_timestamp π
If TRUE (the default), parse() will match complicated timestamps against %y. For example, "2001-10-23--30,2002-02-28" is a range from the 23rd to the 30th of October 2001, and the 28th of February of 2002. According to ISO, "--" can be replaced by "/" as well. And for convenience, the leading 0 can be omitted from the fields which ISO requires to be 2-digit.
π comment_remove_date π
When extracting the date from comment fields, remove the recognized portion even if it's human readable (e.g., "Recorded on 2014-3-23") if TRUE. Current default: FALSE.
π« default_language π«
The language used to select ID3v2 frames, and to choose the "COMM" ID3v2 frame accessed in the comment() method (default is 'XXX'; if it's not "XXX", this should be a lowercase 3-letter abbreviation according to ISO-639-2).
π default_descr_c π
The description field used to choose the "COMM" ID3v2 frame accessed in the comment() method. Defaults to ''.
π«§ id3v2_frame_empty_ok π«§
When setting the individual id3v2 frames via ParseData, don't remove the frames that are set to an empty string. Default 0 (empty means 'remove').
π₯ id3v2_minpadding π₯
The minimal padding to reserve after the ID3v2 tag when writing (default 128).
β¨ id3v2_sizemult β¨
On top of id3v2_minpadding, insert padding to make the file size a multiple of this when writing the ID3v2 tag (default 512). Should be a power of 2.
π
id3v2_shrink π
If TRUE, when writing the ID3v2 tag, shrink the file if needed (default FALSE).
πΊ id3v2_mergepadding πΊ
If TRUE, when writing the ID3v2 tag, consider the 0-bytes following the ID3v2 header as writable space for the tag (default FALSE).
β update_length β
If TRUE, when writing the ID3v2 tag, create a "TLEN" tag if the duration is known (as it is after calling methods like total_secs, or interpolating the duration value). If this field is 2 or more, force creation of the ID3v2 tag by update_tags() if the duration is known.
π translate_* π
FALSE, or a subroutine used to munch a field "*" (out of "title track artist album comment year genre comment_collection comment_track title_track artist_collection person") into some "normalized" form. It takes two arguments: the MP3::Tag object, and the current value of the field.
That second argument may also have the form [value, handler], where handler is the string identifying the handler which returned the value.
π¦ short_person π¦
Similar to translate_person, but the intent here is for this subroutine to translate a personal name field into a shortest "normalized" form.
π― person_frames π―
The list of ID3v2 frames subject to normalization via the translate_person handler; current default is TEXT TCOM TXXX[TPE1] TPE1 TPE3 TOPE TOLY TMCL TIPL TENC TXXX[person-file-by]. Used by select_id3v2_frame_by_descr(), frame_translate(), frames_translate().
π id3v2_missing_fatal π
If TRUE, interpolating ID3v2 frames (like via "%{TCOM}") when the ID3v2 tag is missing is a fatal error. If false (the default), in those cases interpolation results in an empty string.
π id3v2_recalculate π
If TRUE, interpolating the whole ID3v2 tag (via "%{ID3v2}") will recalculate the tag even if its contents weren't modified.
π― parse_minmatch π―
May be 0, 1, or a list of "%"-escapes (matching any string) which should be matched non-greedily by parse() and friends. So like, parsing 'Adagio - Andante - Piano Sonata' via '%t - %l' gives different results for the settings 0 and 1; note that the greediness of %l doesn't matter, so the value of 1 is equivalent to the value of "t" for this particular pattern.
π§ͺ id3v23_unsync_size_w π§ͺ
An old experimental flag to test why ITunes refuses to handle unsynchronized tags (it does not help, see id3v23_unsync). The idea was that version 2.3 of the standard isn't clear about the frame size field, whether it's the size of the frame after unsynchronization, or not. We assume that this size is the one before unsynchronization (as in v2.2). Setting this value to 1 will assume another interpretation (as in v2.4) for write.
π¨ id3v23_unsync π¨
Some broken MP3 players (e.g., ITunes, at least up to v6) refuse to handle unsynchronized (i.e., written as the standard requires it) tags; they may need this to be set to FALSE. Default: TRUE.
(Some details, because iykyk: by definition, MP3 files should only contain combinations of bytes "FF F*" or "FF E*" at the start of audio frames ("synchronization" points). ID3v2 standards take this into account, and support storing raw tag data in a format which doesn't contain these combinations of bytes [via "unsynchronization"]. Itunes etc. don't only emit broken MP3 files [which cause severe hiccups in players which don't know how to skip ID3v2 tags, like most settop DVD players], they also refuse to read ID3v2 tags written in a correct, unsynchronized, format. π)
(Also note that the issue of synchronization is applicable to ID3v1 tags too; however, since this data is near the end of the file, many players are able to recognize that the synchronization points in an ID3v1 tag can't start a valid frame, since there isn't enough data to read; some other players would hiccup anyway if ID3v1 contains these combinations of bytes...)
π encoded_v1_fits π
If FALSE (the default), data containing "high bit characters" is considered to not fit the ID3v1 tag if one of the following conditions holds:
"encode_encoding_v1"is set (so the resulting ID3v1 tag isn't standard-complying, thus ambiguous without ID3v2), or"encode_encoding_v1"is not set, but"decode_encoding_v1"is set (thus a read+write operation isn't idempotent for the ID3v1 tag).
With the default setting, these problems are resolved as far as (re)encoding of the ID3v2 tag is non-ambiguous (which holds with the default settings for ID3v2 encoding). π«Ά
decode_encoding_v1,encode_encoding_v1,decode_encoding_v2,decode_encoding_filename,decode_encoding_inf,decode_encoding_cddb_file,decode_encoding_cue,decode_encoding_files,encode_encoding_filesβ these are the encodings forID3v1, for non-Unicode frames ofID3v2, for filenames, for external files, for.inffiles, forCDDBfiles, for.cuefiles, and for user-specified files, in that order bestie, don't mix them up π . A value of0meanslatin1.
The default values for decode_encoding_* come from the matching MP3TAG_DECODE_*_DEFAULT environment variable (and yes, the * there stands for the uppercased last component of the name, so like MP3TAG_DECODE_V1_DEFAULT energy). If that variable isn't set, it falls back to MP3TAG_DECODE_DEFAULT. Same deal for encode_encoding_v1: its default comes from MP3TAG_ENCODE_V1_DEFAULT or MP3TAG_ENCODE_DEFAULT, and if neither exists, from whatever decode_encoding_v1 is set to. And encode_encoding_files? Literally the same pattern, no cap.
Ok so heads up: decode_encoding_v2 has no encode twin. It can also be disabled per tag through the effects of ignore_trusted_encoding0_v2 plus the corresponding frame TXXX[trusted_encoding0_v2] sitting in the tag. Also keep in mind that the ID3v1 standard requires the encoding to be latin1 (so it doesn't even store the encoding anywhere) β which honestly makes no sense at all, and a lot of this module's effort gets spent fixing that unfortunate little flaw. See "Problems with ID3 format".
ignore_trusted_encoding0_v2β if FALSE (that's the default), and the frameTXXX[trusted_encoding0_v2]is set to TRUE, then the setting ofdecode_encoding_v2just gets ignored. β¨id3v2_set_trusted_encoding0β if TRUE (default!), and frames get converted from the givendecode_encoding_v2into a standard-conforming encoding, then a frameTXXX[trusted_encoding0_v2]with a TRUE value gets added. The whole point is to make multi-step updates possible whendecode_encoding_v2is in play β withid3v2_set_trusted_encoding0TRUE andignore_trusted_encoding0_v2FALSE (both defaults, slay), editing of tags can be idempotent.id3v2_fix_encoding_on_writeβ if TRUE anddecode_encoding_v2is defined, the ID3v2 frames get converted to standard-conforming encodings on write. Default is FALSE, so don't expect it for free.id3v2_fix_encoding_on_editβ if TRUE (default, bestie) anddecode_encoding_v2is defined (and it's not disabled via aTXXX[trusted_encoding0_v2]frame plus theignore_trusted_encoding0_v2setting), a CYA action happens whenever an edit might cause confusion. More precisely: adding an ID3v2 frame that's essentially affected bydecode_encoding_v2would convert other frames to a standard-conforming encoding β and would setTXXX[trusted_encoding0_v2]ifid3v2_set_trusted_encoding0requires it.
Remember that added frames are always encoded in a standard-conformant way; that action above is what avoids mixing non-standard-conformant frames with standard-conformant frames. And a mix like that could not be cleared up by setting decode_encoding_v2! Also keep in mind this doesn't touch frames containing characters above 0x255 β those are always written in Unicode, so they're unaffected by decode_encoding_v2.
id3v2_frames_autofillβ a hash of suggested ID3v2 frames to autogenerate based on whatever extra info is available. Keys are frame descriptors (things likeTXXX[cddb_id]), and the values say whether an ID3v2 tag should be created if it wasn't there already.
This variable gets inspected by the method id3v2_frames_autofill, which is not called automatically when the tag is accessed β but scripts using the module can call it. π«Ά
The default: force creation of the tag for the TXXX[MCDI-fulltoc] frame, and do not force creation for TXXX[cddb_id] and TXXX[cdindex_id].
local_cfg_fileβ the name of the configuration file read at startup by the methodparse_cfg(); it gets~-substituted; defaults to~/.mp3tagprc.prohibit_v24β if FALSE (default), reading of ID3v2.4 is allowed (it's not fully supported, but most things work acceptably enough, ngl).write_v24β if FALSE (default), writing of ID3v2.4 is prohibited (it's not fully supported; allow it on your own risk, fr fr).name_for_field_normalizationβ interpolation of this string is used as a person name to normalize title-like fields. Defaults to%{composer}.extra_config_keysβ a list of extra config keys (default is empty); setting these won't cause warnings, and won't affect howMP3::Tagoperates. Apps using this module can add to this list so they can be configured the same wayMP3::Tagis configured. β¨is_writableβ holds either a boolean value, or a method name plus argument list to call, deciding whether the tag may be added to the file. Defaults towritable_by_extension().writable_extensionsβ a list of extensions (case insensitive) for which the tag may be added to the file. Current default ismp3 mp2 id3 tag ogg mpg mpeg mp4 aiff flac ape ram mpc(extracted from ExifTool docs; may be tuned later, so don't get too attached π).*β later there will probably be more things to configure. Iconic.
get_config
$opt_array = $mp3->get_config("item");
When object options get set or get for the first time, the global options are propagated into the object options. (So if global options change later? Those changes are not inherited. Sorry bestie, that's just how it is.)
get_config1
$opt = $mp3->get_config1("item");
Just like get_config(), but it returns UNDEF if no config array is present, or the first entry of the array otherwise.
name_for_field_normalization
$name = $mp3->name_for_field_normalization;
Returns the "person name" to use for normalization of title-like fields; it's the result of interpolating the configuration variable name_for_field_normalization (which defaults to %{composer} β and that, by default, expands the same as %{TCOM|a}). π
pure_filetags
$data = $mp3->pure_filetags()->autoinfo;
Configures $mp3 to not read anything except the pure ID3v2 or ID3v1 tags, and to not postprocess them. Returns the object reference itself, so you can chain method calls like a main character. π
get_user
$data = $mp3->get_user($n); # n-th piece of user scratch space
Queries an entry in a scratch array ($n=3 corresponds to %{U3}).
set_user
$mp3->set_user($n, $data); # n-th piece of user scratch space
Sets an entry in a scratch array ($n=3 corresponds to %{U3}).
set_id3v2_frame
$mp3->set_id3v2_frame($name, @values);
When called with only $name as the argument, it removes the specified frame (if it existed at all). Otherwise it sets the frame, passing the specified @values to the add_frame() function of MP3::Tag::ID3v2. (The old value gets removed, don't worry.)
get_id3v2_frames
($descr, @frames) = $mp3->get_id3v2_frames($fname);
Returns the specified frame(s); it has the same API as MP3::Tag::ID3v2::get_frames, but it also returns undef if there's no ID3v2 tag present. πΈ
delete_tag
$deleted = $mp3->delete_tag($tag);
$tag should be either ID3v1 or ID3v2. Deletes the tag if it's present. Returns FALSE if the tag isn't present.
is_id3v2_modified
$frame = $mp3->is_id3v2_modified();
Returns TRUE if an ID3v2 tag exists and was modified after creation.
select_id3v2_frame
$frame = $mp3->select_id3v2_frame($fname, $descrs, $langs [, $VALUE]);
Returns the specified frame(s); same API as frame_select in MP3::Tag::ID3v2 (the args are the frame name, the list of wanted Descriptors, the list of wanted Languages, and possibly the new contents β where undef means deletion). For read-only access it returns empty if there's no ID3v2 tag present, or if no frame is found.
If new contents is specified, ALL the existing frames matching the specification get deleted. All of them. Periodt. π
have_id3v2_frame
$have_it = $mp3->have_id3v2_frame($fname, $descrs, $langs);
Returns TRUE if the specified frame(s) exist; same API as MP3::Tag::ID3v2::frame_have (args are the frame name, list of wanted Descriptors, list of wanted Languages).
get_id3v2_frame_ids
$h = $mp3->get_id3v2_frame_ids();
print " $_ => $h{$_}" for keys %$h;
Returns a hash reference with the short names of the ID3v2 frames present in the tag as keys (and a long description of the meaning as values), or FALSE if no ID3v2 tag is present. See MP3::Tags::ID3v2::get_frame_ids for the deets.
id3v2_frame_descriptors
Returns the list of human-readable "long names" of frames (stuff like COMM(eng)[lyricist birthdate]), perfect for interpolation or for select_id3v2_frame_by_descr(). β¨
select_id3v2_frame_by_descr
have_id3v2_frame_by_descr
Similar to select_id3v2_frame() and have_id3v2_frame(), except instead of the arguments $fname, $descrs, $langs they take one single string shaped like this:
NAME(langs)[descr]
Both the (langs) and [descr] parts may be omitted; langs should hold a comma-separated list of the languages you need. The semantics are similar to MP3::Tag::ID3v2::frame_select_by_descr_simpler.
You're allowed to have NAME in the form FRAMnn; the nn-th frame with name FRAM gets chosen (it's -1-based: the first frame is FRAM, the second is FRAM00, the third is FRAM01, etc. β for a more user-friendly scheme, use langs of the form #NNN, with NNN being 0-based; see get_frame_ids() in MP3::Tag::ID3v2).
$frame = $mp3->select_id3v2_frame_by_descr($descr [, $VALUE1, ...]);
$have_it = $mp3->have_id3v2_frame_by_descr($descr);
select_id3v2_frame_by_descr() will also apply the normalizer from the config setting translate_person if the frame name matches one of the elements of the configuration setting person_frames.
$c = $mp3->select_id3v2_frame_by_descr("COMM(fre,fra,eng,#0)[]");
$t = $mp3->select_id3v2_frame_by_descr("TIT2");
$mp3->select_id3v2_frame_by_descr("TIT2", "MyT"); # Set/Change
$mp3->select_id3v2_frame_by_descr("RBUF", $n1, $n2, $n3); # Set/Change
$mp3->select_id3v2_frame_by_descr("RBUF", "$n1;$n2;$n3"); # Set/Change
$mp3->select_id3v2_frame_by_descr("TIT2", undef); # Remove
π REMEMBER, bestie: whenselect_id3v2_frame_by_descr()is used for modification, ALL the frames it found get deleted before a new one is added. Not some. All of them. For the gory details, go readframe_selectinMP3::Tag::ID3v2.
π frame_translate π
$mp3->frame_translate('TCOM'); # Normalize TCOM ID3v2 frame
So like, assuming the frame value is a person's name, this normalizes the value using the personal-name normalization logic (that's the translate_person configuration value doing the work β¨). The frame gets updated, but the tag is not written back β so don't come crying later, okay? Also the frame has to be in the list of personal-names frames (the person_frames configuration value), no exceptions. π
π frames_translate π
Literally the same vibe as frame_translate(), except it updates all the frames sitting in the person_frames configuration value. Bulk mode. Slay. π
π¦ copy_id3v2_frames($from, $to, $overwrite, [$keep_flags, $f_ids]) π¦
Copies the frames you asked for between two MP3::Tag objects, $from and $to. Unless you pass $keep_flags, the copied frames get their flags cleared β fresh start energy. If the array reference $f_ids isn't given, then all the frames are considered (except GRID and TLEN, they're excluded, sorry babes) β and that's all subject to $overwrite, obviously. If you do pass $f_ids, it should hold the short frame ids you want considered. Oh and the Group ID flag is always cleared, no cap.
Now the $overwrite tea β:
- If
$overwriteis'delete', frames in$towith the same descriptors (as returned byget_frame_descr()) get deleted first, and then all the specified frames are copied. - If
$overwriteis FALSE, only frames whose descriptors are not already present in$toget copied.
β οΈ If one of these two conditions is not met, the result may be not conformant to standards. So like, be careful bestie.
Returns the count of copied frames. π
π§ _Data_to_MIME π§
Internal method that pulls the MIME type out of a string containing the image file content. For data it doesn't recognize, it hands you back application/octet-stream β unless you gave that extra TRUE argument, then it doesn't. π
$format = $id3->_Data_to_MIME($data);
Right now, only the first 4 bytes of the string get inspected. Short attention span, iconic behavior. β¨
πΈ shorten_person πΈ
$string = $mp3->shorten_person($person_name);
Shortens $person_name as a personal name, according to the short_person configuration setting. βοΈ
π normalize_person π
$string = $mp3->normalize_person($person_name);
Normalizes $person_name as a personal name, according to the translate_person configuration setting. π«Ά
π id3v2_frames_autofill π
$mp3->id3v2_frames_autofill($force);
Generates the missing tags from the list in the id3v2_frames_autofill configuration variable. And the tags have to come from this short little list the method actually knows how to handle, no improvising:
TXXX[MCDI-fulltoc]: filled from file audio_cd.toc in directory of the
audio file. [Create this file with
readcd -fulltoc dev=0,1,0 -f=audio_cd >& nul
modifying the dev (and redirection per your shell). ]
TXXX[cddb_id]
TXXX[cdindex_id]: filled from the result of the corresponding method
(which may extract from .inf or cddb files).
Existing frames are not modified unless you pass the $force option β and when $force is true, an ID3v2 tag will be created even if it wasn't there before. Manifesting it into existence. π
π₯ interpolate π₯
$string = $mp3->interpolate($pattern)
Interpolates the %-escapes in $pattern using the info from your $mp3 tags. The escape syntax is similar to the one in sprintf():
% [ [FLAGS] MINWIDTH] [.MAXWIDTH] ESCAPE
The only FLAGS it recognizes are - (for left-alignment inside the MINWIDTH-wide field), ' ' (a SPACE), and 0 (which denotes the fill character to use), plus an arbitrary character in parentheses (which becomes the fill character). MINWIDTH and MAXWIDTH should be numbers. β¨
The short ESCAPEs get swapped out like this:
%β a literal%tβ titleaβ artistlβ albumyβ yeargβ genrecβ commentnβ trackfβ filename without the directory pathFβ filename with the directory pathDβ the directory path of the filenameEβ file extensioneβ file extension without the leading dotAβ absolute filename without extensionBβ filename without the directory part and extensionNβ filename as originally given without extension
And then the mpeg / stream-info girlies:
vβmpeg_versionLβmpeg_layer_romanrβbitrate_kbpsqβfrequency_kHzQβfrequency_HzSβtotal_secs_intMβtotal_millisecs_intmβtotal_minsmLβleftover_minsHβtotal_hourssβleftover_secsSLβleftover_secs_truncMLβleftover_msecSMLβleftover_secs_floatCβis_copyrighted_YNpβframes_padded_YNoβchannel_modeuβframes
Image-file ones β and heads up, h, w and iT are the 3 that need image files, with Image::Size or Image::ExifData required:
hβheightwβwidthiTβimg_typemTβmime_typemPβmime_Pretype(the capitalized first part ofmime_type)aRβaspect_ratio(width/height)a3βaspect_ratio3(3 decimal places after the dot)aIβaspect_ratio_inverted(height/width)bDβbit_depth
And the CDDB crew:
aCβ collection artist (fromCDDB_File)tTβ track title (fromCDDB_File)cCβ collection comment (fromCDDB_File)cTβ track comment (fromCDDB_File)iCβ CDDB idiIβ CDIndex id
π Multi-char escapes must be enclosed in braces, as in%{SML}or%.5{aR}.
Additional multi-char escapes get interpreted like this:
- Names of ID3v2 frames are replaced by their text values (empty for missing frames).
- The strings
n1andn2are replaced by the "pure track number" and the "max track number". (This lets both formats work βN1andN1/N2fortrack, the second one meaning track N1 of N2.) Usen0to padn1with leading 0 to the width ofn2(or to 2 if there's no n2). Same deal form1andm2, except with the disk (media) number instead of the track number; and usemAto encodem1as a letter (seedisk_alphanum()). π’ - The strings
ID3v1andID3v2are replaced by the whole ID3v1/2 tag. (Interpolation ofID3v2for an unmodified tag is subject to theid3v2_recalculateconfiguration variable.) These can pull double duty as conditionals too, with:. π - Strings of the form
FRAM(list,of,languages)[description]get replaced by the firstFRAMframe with the descriptordescriptionin the specified comma-separated list of languages. Instead of a language (ID3v2 uses lowercase 3-char ISO-639-2 language notations) you can use a string of the form#Numberβ so like,#4means the 4th FRAM frame, or FRAM04. An empty string for the language means any language. This also works as a condition for conditional interpolation.- Any one of the list of languages and the description can be omitted; that means either the frame
FRAMhas no language or descriptor associated, or that no restriction should be applied. - An unknown language should be denoted as
XXX(in uppercase!). The language match is case-insensitive. π
- Any one of the list of languages and the description can be omitted; that means either the frame
- Several descriptors of the form
FRAM(list,of,languages)[description]β the ones we just talked about β can be combined together with&; the non-empty expansions get joined together with the value of the configuration variableampersand_joiner(default;). Example:
%{TXXX[pre-title]&TIT1&TIT2&TIT3&TXXX[post-title]}
- Strings of the form
method(list,of,packages)[arg1][arg2]get replaced by the result of callingmethod(with the given arguments) in one of the specified known subpackages (so forInf,MP3::Tag::Infis used, bestie). Any number of arguments is supported. Instead of a long name formethod, you can use its standard shortcut (liketfortitle). Example:
$mp3->interpolate('%{t(ID3v1,Cue)}')
That returns the title from the ID3v1 tag, or (if it's not there) from a cue sheet. And yes, you can use this in conditionals and all that too. π
dfollowed by NUMBER is replaced by the NUMBER-th component of the directory name (with 0 corresponding to the last component).Dfollowed by NUMBER is replaced by the directory name with NUMBER components stripped.Ufollowed by NUMBER is replaced by the NUMBER-th component of the user scratch array.- If the string starts with
FNAME:β if the frame FNAME doesn't exist, the escape is ignored; otherwise the rest of the string is reinterpreted. π - Strings starting with
!FNAME:are treated the same way, but with the test inverted. - If the string starts with
FNAME||β if the frame FNAME exists, the part after||is ignored; otherwise the part before||is ignored and the rest is reinterpreted. - If the string starts with
FNAME|β if the frame FNAME exists, the part after|is ignored; otherwise the part before|is ignored and the rest is reinterpreted as if it started with%{. - Strings starting with
LETTER":"or!"LETTER":"are treated like the ID3v2 conditionals above, except the condition is that the corresponding escape expands to a non-empty string. Same applies to non-time-related 2-char escapes and user variables. - Likewise for strings starting with
LETTER"|"orLETTER"||". - For strings of the form
nmP[VALUE]orshP[VALUE], VALUE is interpolated first, then normalized or shortened as a personal name (according to thetranslate_personorshort_personconfiguration setting). π composerorperformeris replaced by the result of calling the corresponding method. πframesβ gets replaced by a space-separated list of the "long names" of ID3v2 frames (go peek atid3v2_frame_descriptors()for those). Wanna use a different separator? Drop it after a slash, like"%{frames/, }", where the separator is COMMA SPACE. β¨_out_frames[QQPRE//QQPOST]β replaced by a verbose listing of frames. "simple" frames are output one-per-line (with the value surrounded by "QQPRE" and "QQPOST"); fields of other frames are output one-per-line. And if you omit the leading_, then"__binary_DATA__"replaces the value of binary fields. π«ΆID3v2-size,ID3v2-pad, andID3v2-strippedβ replaced by the size of the ID3v2 tag in bytes, the amount of 0-padding at the end of the tag (not counting one extra 0 byte at the end of the tag which may be needed for unsyncing if the last char is\xFF), and the size without padding. Currently, for a modified ID3v2 tag, what is returned reflects the size on disk (i.e., before modification). lowkey important, bestieID3v2-modifiedβ replaced by'modified'if ID3v2 is present and is modified in memory; otherwise it's replaced by an empty string.- For strings of the form
"I(FLAGS)VALUE", VALUE is interpolated with flags in FLAGS (see"interpolate_with_flags"). If FLAGS does not contain"i", VALUE should have"{}"and"\"backwacked. - For strings of the form
"T[FORMAT]", FORMAT is split on comma, and the resulting list of formats is used to convert the duration of the audio to a string using the methodformat_time(). (E.g.,"%{T[=>m,?H:,{mL}]}"would print duration in (optional) hours and minutes rounded to the closest minute.) β±οΈ
The default for the fill character is SPACE. Fill character should preceed "-" if both are given. Example:
Title: %(/)-12.12t%{TIT3:; TIT3 is %\{TIT3\}}%{!TIT3:. No TIT3 is present}
will result in
Title: TITLE///////; TIT3 is Op. 16
if title is "TITLE", and TIT3 is "Op. 16", and
Title: TITLE///////. No TIT3 is present
if title is "TITLE", but TIT3 is not present. the way that just WORKS π
Fat content: %{COMM(eng,fra,fre,rus,)[FatContent]}
will print the comment field with Description "FatContent" prefering the description in English to one in French, Russian, or any other language (in this order). (I do not know which one of terminology/bibliography codes for French is used, so for safety include both.) π
Composer: %{TCOM|a}
will use the ID3v2 field "TCOM" if present, otherwise uses %a (this is similar to
Composer: %{composer}
but the latter may be subject to (different) normalization, and/or configuration variables).
Interpolation of ID3v2 frames uses the minimal possible non-ambiguous backslashing rules: the only backslashes needed are to protect the innermost closing delimiter ("]" or "}") appearing as a literal character, or to protect backslashes immediately preceding such literal, or the closing delimiter. E.g., the pattern equal to
%{COMM(eng)[a\b\\c\}\]end\\\]\\\\]: comment `a\b\\c\\\}]end\]\\' present}
checks for the presence of comment with the descriptor "a\b\\c\}]end\]\\". Note that if you want to write this string as a Perl literal, a lot of extra backslashes may be needed (unless you use "<<'FOO'" HERE-document). π
%{T[?Hh,?{mL}m,{SML}s]}
for a file of duration 2345.62sec will result in "39m05.62s", while
%{T[?H:,?{mL}:,{SL},?{ML}]}sec
will result in "39:05.620sec".
β¨ interpolate_with_flags β¨
@results = $mp3->interpolate_with_flags($text, $flags);
Processes $text according to directives in the string $flags; $flags is split into separate flag characters; the meanings (and order of application) of flags are
i interpolate via $mp3->interpolate
f interpret (the result) as filename, read from file
F if file does not exist, it is not an error
B read is performed in binary mode (otherwise
in text mode, modified per
'decode_encoding_files' configuration variable)
l split result per 'parse_split' configuration variable
n as l, using the track-number-th element (1-based)
in the result
I interpolate (again) via $mp3->interpolate
b unless present, remove leading and trailing whitespace
With "l", may produce multiple results. May be accessed via interpolation of "%{I(flags)text}". π¦
πΈ parse_rex($pattern, $string) πΈ
Parse $string according to the regular expression $pattern with "%"-escapes "%%, %a, %t, %l, %y, %g, %c, %n, %e, %E" etc. The meaning of escapes is the same as for method "interpolate"(); but (with the exception of "%%") they are used not for expansion, but for matching a part of $string suitable to be a value for these fields. Returns false on failure, a hash reference with parsed fields otherwise (with %a setting the field "author", etc). π
Some more escapes are supported: "%=a, %=t, %=l, %=y, %=g, %=c, %=n, %=e, %=E, %=A, %=B, %=D, %=f, %=F, %=N, %={WHATEVER}" match substrings which are current values of artist/title/etc ("%=n" also matches leading 0s; actual file-name matches ignore the difference between "/" and "\", between one and multiple consequent dots (if configuration variable "parse_filename_merge_dots" is true (default)) and are case-insensitive if configuration variable "parse_filename_ignore_case" is true (default); moreover, %n, %y, "%=n", "%=y" will not match if the string-to-match is adjacent to a digit). Double "=" if you want to match to fail when the corresponding conditional "%"-escape would fail (a missing field, or a zero-length field for required fields). π
The escapes "%{U<number>}" and escapes of the forms "%{ABCD}" match any string; the corresponding hash key in the result hash is what is inside braces; here "ABCD" is a 4-letter word possibly followed by 2-digit number (as in names of ID3v2 tags), or what can be put in '%{FRAM(lang,list)[description]}'.
$res = $mp3->parse_rex( qr<^%a - %t\.\w{1,4}$>,
$mp3->filename_nodir ) or die;
$author = $res->{author};
2-digit numbers, or number1/number2 with number1,2 up to 999 are allowed for the track number (the leading 0 is stripped); 4-digit years in the range 1000..2999 are allowed for year. Alternatively, if option year_is_timestamp is TRUE (default), year may be a range of timestamps in the format understood by ID3v2 method year() (see "year" in MP3::Tag::ID3v2).
The escape %E matches the REx in the configuration variable "extension"; the escape %e matches the part of %E after the leading dot.
In list context, also returns an array reference with %{handler} groups parsed (if present). Such groups can match everything, and a successful match gives an array element with "[$method, $packages, $args, $matched]".
Currently the regular expressions with capturing parens are not supported. fr fr, do not try it π
π parse_rex_prepare($pattern) π
Returns a data structure which later can be used by parse_rex_match(). These two are equivalent:
$mp3->parse_rex($pattern, $data);
$mp3->parse_rex_match($mp3->parse_rex_prepare($pattern), $data);
This call constitutes the "slow part" of the parse_rex() call; it makes sense to factor out this step if the parse_rex() with the same $pattern is called against multiple $data. β
π parse_rex_match($prepared, $data) π
Matches $data against a data structure returned by parse_rex_prepare(). These two are equivalent:
$mp3->parse_rex($pattern, $data);
$mp3->parse_rex_match($mp3->parse_rex_prepare($pattern), $data);
π parse($pattern, $string) π
Parse $string according to the string $pattern with "%"-escapes "%%, %a, %t, %l, %y, %g, %c, %n, %e, %E". The meaning of escapes is the same as for "interpolate". See "parse_rex($pattern, $string)" for more details. Returns false on failure, a hash reference with parsed fields otherwise.
$res = $mp3->parse("%a - %t.mp3", $mp3->filename_nodir) or die;
$author = $res->{author};
2-digit numbers are allowed for the track number; 4-digit years in the range 1000..2999 are allowed for year.
π§ parse_prepare($pattern) π§
Returns a data structure which later can be used by parse_rex_match(). This is a counterpart of parse_rex_prepare() used with non-regular-expression patterns. These two are equivalent:
$mp3->parse($pattern, $data);
$mp3->parse_rex_match($mp3->parse_prepare($pattern), $data);
This call constitutes the "slow part" of the parse() call; it makes sense to factor out this step if the parse() with the same $pattern is called against multiple $data. π
π filename(), abs_filename(), filename_nodir(), filename_noextension(), filename_nodir_noextension(), abs_filename_noextension(), dirname([$strip_levels]), filename_extension(), filename_extension_nodot(), dir_component([$level]) π
$filename = $mp3->filename();
$abs_filename = $mp3->abs_filename();
$filename_nodir = $mp3->filename_nodir();
$abs_dirname = $mp3->dirname();
$abs_dirname = $mp3->dirname(0);
$abs_parentdir = $mp3->dirname(1);
$last_dir_component = $mp3->dir_component(0);
Return the name of the audio file: either as given to the new() method, or absolute, or directory-less, or originally given without extension, or directory-less without extension, or absolute without extension, or the directory part of the fullname only, or filename extension (with dot included, or not). π
The extension is calculated using the config() value "extension".
The dirname() method takes an optional argument: the number of directory components to strip; the "dir_component($level)" method returns one component of the directory (to get the last use 0 as $level; this is the default if no $level is specified).
The configuration option "decode_encoding_filename" can be used to specify the encoding of the filename; all these functions would use filename decoded from this encoding. obsessed with how tidy this is β¨
mpeg_version()mpeg_layer()mpeg_layer_roman()is_stereo()is_vbr()bitrate_kbps()frequency_Hz()frequency_kHz()size_bytes()total_secs()total_secs_int()total_secs_trunc()total_millisecs_int()total_mins()leftover_mins()leftover_secs()leftover_secs_float()leftover_secs_trunc()leftover_msec()time_mm_ss()is_copyrighted()is_copyrighted_YN()frames_padded()frames_padded_YN()channel_mode_int()frames()frame_len()vbr_scale()
okay bestie, all of these hand you back info about what's actually inside your MP3 file β¨. But heads up: if that info isn't already cached in ID3v2 tags (not implemented yet, rip), then using these methods means you need the module MP3::Info installed. And because these calls get redirected to MP3::Info, whatever comes back is subject to the exact same restrictions as that module's get_mp3info() method β meaning specifically that the info about frame number and frame length is only approximate. like, vibes-based numbers, not receipts π.
vbr_scale() comes from the VBR header. total_secs() is not necessarily an integer, but total_secs_int() and total_secs_trunc() are (first one is rounded, second one is truncated). time_mm_ss() has the format "MM:SS". The *_YN flavors return the value as a string, like Yes or No. mpeg_layer_roman() returns the value as a roman numeral ποΈ. And channel_mode() takes values in 'stereo', 'joint stereo', 'dual channel', 'mono'.
β¨ format_time β¨
$output = $mp3->format_time(67456.123, @format);
Formats time according to @format, which should be a list of format descriptors π. Each format descriptor is either a simple letter, or a string in braces appropriate to be put after "%" in an interpolated string. A format descriptor can be followed by a literal string to be put as a suffix, and can be preceded by a question mark, which says that this part of format should be printed only if needed.
Leftover minutes and seconds are formatted 0-padded to width 2 if they are preceded by more coarse units π. Similarly, leftover milliseconds are printed with a leading dot, and 0-padded to width 3.
Two examples of useful @formats are
qw(?H: ?{mL}: {SML})
qw(?Hh ?{mL}m {SL} ?{ML})
Both will print hours, minutes, and milliseconds only if needed. The second one will use 3 digit-format after a point, the first one will not print the trailing 0s of milliseconds. The first one uses ":" as separator of hours and minutes, the second one will use "h m" π°οΈ.
Optionally, the first element of the array may be of the form "=>U", here "U" is one of "h m s". In this case, duration is rounded to closest hours, min or second before processing. (E.g., 1.7sec would print as 1 with @formats above, but would print as 2 if rounded to seconds.) π§
can_write()
Checks permission to write per the configuration variable "is_writable" β
.
can_write_or_die($mess)
As can_write(), but die()s on non-writable files with a meaningful error message ($mess is prepended to the message) π.
die_cant_write($mess)
die() with the same message as can_write_or_die().
writable_by_extension()
Checks that the extension is (case-insensitively) in the list given by the configuration variable "writable_extensions".
update_tags( [ $data, [ $force2 ]] )
$mp3 = MP3::Tag->new($filename);
$mp3->update_tags(); # Fetches the info, and updates tags
$mp3->update_tags({}); # Updates tags if needed/changed
$mp3->update_tags({title => 'This is not a song'}); # Updates tags
This method updates ID3v1 and ID3v2 tags β the ID3v2 one only if the in-memory copy contains any data, or $data does not fit ID3v1 restrictions, or the $force2 argument is given β with the information about title, artist, album, year, comment, track, genre from the hash reference $data πΈ. The format of $data is the same as the one returned from autoinfo() (with or without the optional argument 'from'). The fields which are marked as coming from ID3v1 or ID3v2 tags are not updated when written to the same tag π.
If $data is not defined or missing, "autoinfo('from')" is called to obtain the data. Returns the object reference itself to simplify chaining of method calls π.
This is probably the simplest way to set data in the tags: populate $data and call this method β no further tinkering with subtags is needed. periodt π
.
extension_is
$mp3->extension_is(@EXT_LIST)
Returns TRUE if the extension of the filename coincides (case-insensitive) with one of the elements of the list π¦.
"parse_cfg( [$filename] )"
Reads configuration information from the specified file (defaults to the value of configuration variable "local_cfg_file", which is "~"-substituted). Empty lines and lines starting with "#" are ignored π. The remaining lines should have format "varname=value"; leading and trailing whitespace is stripped; there may be several lines with the same "varname"; this sets list-valued variables.
π ENVIRONMENT π
Some defaults for the operation of this module (and/or scripts distributed with this module) are set from environment π±. Assumed encodings (0 or encoding name): for read access:
MP3TAG_DECODE_V1_DEFAULT MP3TAG_DECODE_V2_DEFAULT
MP3TAG_DECODE_FILENAME_DEFAULT MP3TAG_DECODE_FILES_DEFAULT
MP3TAG_DECODE_INF_DEFAULT MP3TAG_DECODE_CDDB_FILE_DEFAULT
MP3TAG_DECODE_CUE_DEFAULT
for write access:
MP3TAG_ENCODE_V1_DEFAULT MP3TAG_ENCODE_FILES_DEFAULT
(if not set, default to the corresponding "DECODE" options.)
Defaults for the above:
MP3TAG_DECODE_DEFAULT MP3TAG_ENCODE_DEFAULT
(if the second one is not set, the value of the first one is used). Value 0 for a more specific variable will cancel the effect of the less specific variables π.
If the "LANG" environment variable indicates "UTF-8" encoding, then the "FILES" flavors default to "utf8" (unless this effect is already achieved by the ${^UNICODE} variable) β¨. This may be disabled by setting "MP3TAG_DECODE_FILES_DEFAULT_RESET" true in the environment (likewise for the "EN"-code flavor).
These variables set default configuration settings for "MP3::Tag"; the values are read during the load time of the module π. After load, one can use config()/get_config() methods to change/access these settings. See "encode_encoding_*" and "encode_decoding_*" in the documentation of the config method. (Note that the "FILES" variant governs file read/written in non-binary mode by "ParseData" in the MP3 module, as well as reading of control files of some scripts using this module, such as typeset_audio_dir.)
π EXAMPLE π
Assume that locally present CDDB files and .inf files are in encoding "cp1251" (this is not supported by "standard", but since the standard supports only a handful of languages, this is widely used anyway), and that one wants "ID3v1" fields to be in the same encoding, but "ID3v2" have an honest (Unicode, if needed) encoding π. Then set
MP3TAG_DECODE_INF_DEFAULT=cp1251
MP3TAG_DECODE_CDDB_FILE_DEFAULT=cp1251
MP3TAG_DECODE_V1_DEFAULT=cp1251
Since "MP3TAG_DECODE_V1_DEFAULT" implies "MP3TAG_ENCODE_V1_DEFAULT", you will get the desired effect both for read and write of MP3 tags π¦.
Additionally, the following (unsupported) variables are currently recognized by ID3v2 code:
MP3TAG_DECODE_UNICODE MP3TAG_DECODE_UTF8
MP3TAG_DECODE_UNICODE (default 1) enables decoding; the target of decoding is determined by MP3TAG_DECODE_UTF8: if 0, decoded values are byte-encoded UTF-8 (every Perl character contains a byte of UTF-8 encoded string); otherwise (default) it is a native Perl Unicode string β¨.
If "MP3TAG_SKIP_LOCAL" is true, local customization files are not loaded π
.
π CUSTOMIZATION π
Many aspects of the operation of this module are subject to certain subtle choices. A lot of effort went into making these choices customizable, by setting global or per-object configuration variables π .
A certain degree of customization of global configuration variables is available via the environment variables π. Moreover, at startup the local customization file ~/.mp3tagprc is read, and defaults are set accordingly.
In addition, to make customization as flexible as possible, ALL aspects of the operation of "MP3::Tag" are subject to local override. Three customization modules
MP3::Tag::User MP3::Tag::Site MP3::Tag::Vendor
are attempted to be loaded if present π. Only the first module (of those present) is loaded directly; if sequential load is desirable, the first thing a customization module should do is to call
MP3::Tag->load_parents()
method.
The customization modules have an opportunity to change global configuration variables on load β¨. To allow more flexibility, they may override any method defined in "MP3::Tag"; as usual, the overridden method may be called using the "SUPER" modifier (see "Method invocation" in perlobj) π§.
E.g., it is recommended to make a local customization file with
eval 'require Normalize::Text::Music_Fields';
for my $elt ( qw( title track artist album comment year genre
title_track artist_collection person ) ) {
no strict 'refs';
MP3::Tag->config("translate_$elt", \&{"Normalize::Text::Music_Fields::normalize_$elt"})
if defined &{"Normalize::Text::Music_Fields::normalize_$elt"};
}
MP3::Tag->config("short_person", \&Normalize::Text::Music_Fields::short_person)
if defined &Normalize::Text::Music_Fields::short_person;
and install the (supplied, in the examples/modules) module Normalize::Text::Music_Fields which enables normalization of person names (to a long or a short form), and of music piece names to canonical forms πΈ.
To simplify debugging of local customization, it may be switched off completely by setting MP3TAG_SKIP_LOCAL to TRUE (in environment) π.
For example, putting
id3v23_unsync = 0
into ~/.mp3tagprc will produce broken ID3v2 tags (but those required by ITunes). π no cap.
β¨ EXAMPLE SCRIPTS β¨
Okay bestie, some example scripts come with this module (either installed, or in directory examples in the distribution); they either use this module, or provide data understood by this module:
mp3info2β perform command line manipulation of audio tags (and more!);audio_renameβ rename audio files according to associated tags (and more!);typeset_mp3_dirβ write LaTeX files suitable for CD covers and normal-size sheet descriptions of hierarchy of audio files;mp3_total_timeβ Calculate total duration of audio files;eat_wav_mp3_headerβ remove WAV headers from MP3 files in WAV containers.fulltoc_2fake_cddbβ converts a CD's "full TOC" to a "fake" CDDB file (header only). Create this file with something like
readcd -fulltoc dev=0,1,0 -f=audio_cd >& nul
run similar to
fulltoc_2fake_cddb < audio_cd.toc | cddb2cddb > cddb.out
dir_mp3_2fake_cddbβ tries to convert a directory of MP3 files to a "fake" CDDB file (header only); assumes that files are a rip from a CD, and that alphabetical sort gives the track order (works only heuristically, since quantization of duration of MP3 files and of CD tracks is so different).
Run similar to
dir_mp3_2fake_cddb | cddb2cddb > cddb.out
inf_2fake_cddbβ tries to convert a directory of.inffiles to a "fake" CDDB file (header only). (Still heuristic, since it can't guess the length of the leader.)
Run similar to
inf_2fake_cddb | cddb2cddb > cddb.out
cddb2cddbβ Reads a (header of) CDDB file from STDIN, outputs (on STDOUT) the current version of the database record. Can be used to update a file, and/or to convert a fake CDDB file to a real one.
(Last four do not use these modules!)
Some more examples:
# Convert from one (non-standard-conforming!) encoding to another
perl -MMP3::Tag -MEncode -wle '
my @fields = qw(artist album title comment);
for my $f (@ARGV) {
print $f;
my $t = MP3::Tag->new($f) or die;
$t->update_tags(
{ map { $_ => encode "cp1251", decode "koi8-r", $t->$_() }, @fields }
);
}' list_of_audio_files
π Problems with ID3 format π
The largest problem with ID3 format is that the first versions of these format were absolutely broken (underspecified). It looks like the newer versions of this format resolved most of these problems; however, in reality they did not (due to unspecified backward compatibility, and grandfathering considerations).
What are the problems with ID3v1? First, one of the fields was artist, which does not make any sense. In particular, different people/publishers would put there performer(s), composer, author of text/lyrics, or a combination of these. The second problem is that the only allowed encoding was iso-8859-1; since most of languages of the world can't be expressed in this encoding, this restriction was completely ignored, thus the encoding is essentially unknown.
Newer versions of ID3 allow specification of encodings; however, since there is no way to specify that the encoding is unknown, when a tag is automatically upgraded from ID3v1, it is most probably assumed to be in the standard iso-8859-1 encoding. Thus impossibility to distinguish "unknown, assumed iso-8859-1" from "known to be iso-8859-1" in ID3v2, essentially, makes any encoding specified in the tag "unknown" (or, at least, "untrusted"). (Since the upgrade [or a chain of upgrades] from the ID3v1 tag to the ID3v2 tag can result in any encoding of the "supposedly iso-8859-1" tag, one cannot trust the content of ID3v2 tag even if it stored as Unicode strings.)
This is why this module provides what some may consider only lukewarm support for encoding field in ID3v2 tags: if done fully automatic, it can allow instant propagation of wrong information; and this propagation is in a form which is quite hard to undo (but still possible to do with suitable settings to this module; see "Examples on dealing with broken encodings" in mp3info2).
Likewise, the same happens with the artist field in ID3v1. Since there is no way to specify just artist, type unknown in ID3v2 tags, when ID3v1 tag is automatically upgraded to ID3v2, the content would most probably be put in the main performer, TPE1, tag. As a result, the content of TPE1 tag is also untrusted - it may contain, e.g., the composer.
In my opinion, a different field should be used for known to be principal performer; for example, the method performer() (and the script mp3info2 shipped with this module) uses %{TXXX[TPE1]} in preference to %{TPE1}.
For example, interpolate %{TXXX[TPE1]|TPE1} or %{TXXX[TPE1]|a} - this will use the frame TXXX with identifier TPE1 if present, if not, it will use the frame TPE1 (the first example), or will try to get artist by other means (including TPE1 frame) (the second example).
π FILES π
There are many files with special meaning to this module and its dependent modules.
*.infβ Files with extension.infand the same basename as the audio file are read by moduleMP3::Tag::Inf, and the extracted data is merged into the information flow according to configuration variableautoinfo.
It is assumed that these files are compatible in format to the files written by the program cdda2wav.
audio.cddbcddb.outcddb.inβ in the same directory as the audio file are read by moduleMP3::Tag::CDDB_File, and the extracted data is merged into the information flow according to configuration variableautoinfo.
(In fact, the list may be customized by configuration variable cddb_files.)
audio_cd.tocβ in the same directory as the audio file may be read by the methodid3v2_frames_autofill()(should be called explicitly) to fill theTXXX[MCDI-fulltoc]frame. Depends on contents of configuration variableid3v2_frames_autofill.~/.mp3tagprcβ By default, this file is read on startup (may be customized by overriding the methodparse_cfg()). By default, the name of the file is in the configuration variablelocal_cfg_file.
π SEE ALSO π
MP3::Tag::ID3v1MP3::Tag::ID3v2MP3::Tag::FileMP3::Tag::ParseDataMP3::Tag::InfMP3::Tag::CDDB_FileMP3::Tag::CueMP3::Tag::ImageExifToolMP3::Tag::ImageSizeMP3::Tag::LastResortmp3info2typeset_audio_dir
Β©οΈ COPYRIGHT Β©οΈ
Copyright (c) 2000-2016 Thomas Geffert, Ilya Zakharevich. All rights reserved.
This program is free software; you can redistribute it and/or modify it under the terms of the Artistic License, distributed with Perl.
π¨ POD ERRORS π¨
Hey! The above document had some coding errors, which are explained below:
Around line 1192:
Expected text after =item, not a bullet
and that's a wrap, bestie! π this page came from perl v5.36.0, dated 2022-12-30, and it's MP3::Tag(3pm) β slay, read it again, periodt. π
β¨
π¦ where this page comes from
- debian bookworm: libmp3-tag-perl 1.16-1 Β· Artistic-1.0-Perl
- debian trixie: libmp3-tag-perl 1.16-1 Β· Artistic-1.0-Perl
- ubuntu noble: libmp3-tag-perl 1.16-1 Β· Artistic-1.0-Perl
- ubuntu resolute: libmp3-tag-perl 1.16-1 Β· Artistic-1.0-Perl
- ubuntu stonking: libmp3-tag-perl 1.16-1 Β· Artistic-1.0-Perl
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms