MP3::Tag(3)
π΅ MP3::Tag(3) β the manual, bestie edition π΅
Okay so this is the MP3::Tag(3) page from User Contributed Perl Documentation, and it's all about reading tags of MP3 audio files. Tag-reading main character energy, honestly. π
π NAME π
MP3::Tag β Module for reading tags of MP3 audio files. That's the whole name vibe. β¨
πΈ SYNOPSIS πΈ
Bestie, here's the exact code vibe. Do not rename anything β this is the whole main-character block:
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
The following low-level access code is discouraged; better use title() etc., title_set() etc., update_tags(), select_id3v2_frame_by_descr() etc. methods on the wrapper $mp3:
# 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();
Please consider using the script mp3info2; it allows simple access to most features of this module via command-line options; see mp3info2.
π«Ά AUTHORS π«Ά
The icons behind this: Thomas Geffert, thg@users.sourceforge.net; Ilya Zakharevich, ilyaz@cpan.org. Respect the OGs. π
β¨ DESCRIPTION β¨
MP3::Tag is a wrapper module to read different tags of mp3 files. It gives you an easy way to access the functions of separate modules that do the handling of reading/writing the tags themselves.
At the moment MP3::Tag::ID3v1 and MP3::Tag::ID3v2 are supported for read and write; MP3::Tag::ImageExifTool, MP3::Tag::Inf, MP3::Tag::CDDB_File, MP3::Tag::File, MP3::Tag::Cue, MP3::Tag::ImageSize, MP3::Tag::LastResort are supported for read access. That covers info obtained by Image::ExifTool (if present), parsing CDDB files, the .inf file, the filename, and the .cue file, plus info obtained via Image::Size (if present). Literally a little tag-reading friend group. π
π£ new()
$mp3 = MP3::Tag->new($filename);
Creates an mp3-object, which can be used to retrieve/set 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 which contains strings identifying the found tags, like "ID3v1", "ID3v2", "Inf", or "CDDB_File" (the last but one if the .inf information file with the same basename as MP3 file is found).
Each found tag can then be accessed with $mp3->{tagname}, where tagname is a string returned by get_tags;
Use the information found 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 the tags. π¦
π new_fake
$obj = MP3::Tag->new_fake();
This method produces a "fake" MP3::Tag object which behaves as an MP3 file without tags. Give a TRUE optional argument if you want to set some properties of this object. Fake it till you make it, but make it a proper 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 new tag of the given type $tagname. You can access it then with $mp3->{$tagname}. At the moment ID3v1 and ID3v2 are supported as tagname.
Returns an tag-object: $mp3->{$tagname}.
πͺ close()
$mp3->close;
You can use close() to explicitly close a file. Normally this is done automatically by the module, so that you do not need to do this.
πΌ genres()
$allgenres = $mp3->genres;
$genreName = $mp3->genres($genreID);
$genreID = $mp3->genres($genreName);
Returns a list of all genres (reference to an array), or the according name or id to a given id or name.
This function is only a shortcut to MP3::Tag::ID3v1->genres.
This can be also called as MP3::Tag->genres; genre goblin mode activated. π
πͺ autoinfo()
($title, $track, $artist, $album, $comment, $year, $genre) = $mp3->autoinfo();
$info_hashref = $mp3->autoinfo();
autoinfo() returns information about the title, track number, artist, album name, the file comment, the year and genre. It can get this information from an ID3v1-tag, an ID3v2-tag, from CDDB file, from .inf-file, and from the filename itself.
It will as default first try to find a ID3v2-tag to get this information. If this cannot be found it tries to find a ID3v1-tag, then to read an CDDB file, an .inf-file, and if these are not present either, it will use the filename to retrieve the title, track number, artist, 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 information or a hashref. The hash has four keys 'title', 'track', 'artist' and 'album' where the information is stored. 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, the second the tag ("ID3v2" or "ID3v1" or "Inf" or "CDDB_File" or "Cue" or "filename") from which it is taken.
(Deprecated name 'song' can be used instead of 'title' as well.)
π¬ comment()
$comment = $mp3->comment(); # empty string unless found
comment() returns comment information. It can get this information from an ID3v1-tag, or an ID3v2-tag (from "COMM" frame with empty <short> field), CDDB file (from "EXTD" or "EXTT" fields), or .inf-file (from "Trackcomment" field).
It will as default first try to find a ID3v2-tag to get this information. If no comment is found there, it tries to find it in a ID3v1-tag, if none present, will try CDDB file, then .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, returns an array reference with the first element being the value, the second the tag (ID3v2 or ID3v1) from which the value is taken.
π
year()
$year = $mp3->year(); # empty string unless found
year() returns the year information. It can get this information from an ID3v2-tag, or ID3v1-tag, or .inf-file, or filename.
It will as default first try to find a ID3v2-tag to get this information. If no year is found there, it tries to find it in a ID3v1-tag, if none present, will try CDDB file, then .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, returns an array reference with the first element being the value, the second the tag (ID3v2 or ID3v1 or filename) from which the value is taken. Year detective era. π΅οΈββοΈ
π§© comment_collection(), comment_track(), title_track(), artist_collection()
Access the corresponding fields returned by parse() method of CDDB_File.
π cddb_id(), cdindex_id()
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 ID3v1 tag, and, if the value does not fit, or force_id3v2 is TRUE, in the ID3v2 tag. Changes are made to in-memory copy only. To propagate to the file, use update_tags() or similar methods.
1οΈβ£ track1()
Same as track(), but strips trailing info: if track() returns "3/12" (which means track 3 of 12), this method returns 3.
2οΈβ£ track2()
Returns the second part of track number (compare with track1()).
0οΈβ£ track0()
Same as track1(), but pads with leading 0s to width of track2(); takes an optional argument (default is 2) giving the pad width in absense of track2().
π½ disk1(), disk2()
Same as track1(), track2(), but with disk-number instead of track-number (stored in "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 number of disks is more than 26, falls back to numeric (e.g, "3/888" will be encoded as 003). Alphabet soup but make it track metadata. π
π¦ mime_type( [$lazy] )
Returns the MIME type as a string. Returns "application/octet-stream" for unrecognized types. If not $lazy, will try harder (via ExifTool, if needed).
π mime_Pretype( [$lazy] )
Returns uppercased first component of MIME type.
π΅ genre()
$genre = $mp3->genre(); # empty string unless found
genre() returns the genre string. It can get this information from an ID3v2-tag or ID3v1-tag.
It will as default first try to find a ID3v2-tag to get this information. If no genre is found there, it tries to find it in a ID3v1-tag, if none present, will try .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, returns an array reference with the first element being the value, the second the tag (ID3v2 or ID3v1 or filename) from which the value is taken.
πΉ composer()
$composer = $mp3->composer(); # empty string unless found
composer() returns the composer. By default, it gets from ID3v2 tag, otherwise returns artist.
You can change the inspected fields with the config() command. Subject to normalization via "translate_composer" or "translate_person" configuration variables.
π€ performer()
$performer = $mp3->performer(); # empty string unless found
performer() returns the main performer. By default, it gets it from ID3v2 tag "TXXX[TPE1]", otherwise from ID3v2 tag "TPE1", otherwise it returns artist. π«Ά
You can change the inspected fields with the config() command. 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
When object options are first set or gotten, the global options are propagated into the object options. (So if global options are changed later, those changes are not inherited. π)
Possible items are:
autoinfoβ Configure the order in which ID3v1-, ID3v2-tag and filename are used byautoinfo. The default is"ParseData, ID3v2, ID3v1, ImageExifTool, CDDB_File, Inf, Cue, ImageSize, filename, LastResort". Options can be elements of the default list. The order you give them toconfigalso sets the orderautoinfouses them. If an option is not present, it will not be used byautoinfo(and other auto-methods if the specific overriding config command was not 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 never be checked here.
$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β Configure the order in which ID3v1- and ID3v2-tag are used by the corresponding methods (e.g.,comment()). Options can be the same as for"autoinfo". The order in which they are given toconfigalso sets the order they are used bycomment(). If an option is not present, then the"autoinfo"option will be used instead.extensionβ Regular expression to match the file extension (including the dot). The default is to match 1..4 letter extensions which are not numbers.composerβ String to put into"%{}"to interpolate to get the composer. Default is'TCOM|a'.performerβ String to put into"%{}"to interpolate to get the main performer. Default is'TXXX[TPE1]|TPE1|a'.parse_dataβ The data used byMP3::Tag::ParseDatahandler; each option is an array reference of the form[$flag, $string, $pattern1, ...]. All the options are processed like this: patterns are matched against$stringuntil one of them succeeds; the information obtained from later options takes precedence over the information obtained from earlier ones.parse_splitβ The regular expression to split the data when parsing with"n"or"l"flags.parse_filename_ignore_caseβ If true (default), callingparse()andparse_rex()with match-filename escapes (such as"%=D") matches case-insensitively.parse_filename_merge_dotsβ If true (default), callingparse()andparse_rex()with match-filename escapes (such as"%=D") does not distinguish a dot and many consequent dots.parse_joinβ String to put between multiple occurrences of a tag in a parse pattern; defaults to'; '. E.g., parsing'1988-1992, Homer (LP)'with pattern'%c, %a (%c)'results in comment set to'1988-1992; LP'with the default value of"parse_join".v2titleβ Configure the elements of ID3v2-tag which are used byID3v2::title(). Options can be"TIT1","TIT2","TIT3"; the present values are combined. If an option is not present, it will not be used byID3v2::title().cddb_filesβ List of files to look for in the directory of MP3 file to get CDDB info.year_is_timestampβ If TRUE (default)parse()will match complicated timestamps against%y; for example,"2001-10-23--30,2002-02-28"is a range from 23rd to 30th of October 2001, and 28th of February of 2002. According to ISO,"--"can be replaced by"/"as well. 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 is human readable (e.g.,"Recorded on 2014-3-23") if TRUE. Current default: FALSE.default_languageβ The language to use to select ID3v2 frames, and to choose"COMM"ID3v2 frame accessed incomment()method (default is'XXX'; if not"XXX", this should be lowercase 3-letter abbreviation according to ISO-639-2).default_descr_cβ The description field used to choose the"COMM"ID3v2 frame accessed incomment()method. Defaults to''.id3v2_frame_empty_okβ When setting the individual id3v2 frames via ParseData, do not remove the frames set to an empty string. Default 0 (empty means 'remove').id3v2_minpaddingβ Minimal padding to reserve after ID3v2 tag when writing (default 128).id3v2_sizemultβ Additionally to"id3v2_minpadding", insert padding to make file size multiple of this when writing ID3v2 tag (default 512). Should be power of 2.id3v2_shrinkβ If TRUE, when writing ID3v2 tag, shrink the file if needed (default FALSE).id3v2_mergepaddingβ If TRUE, when writing ID3v2 tag, consider the 0-bytes following the ID3v2 header as writable space for the tag (default FALSE).update_lengthβ If TRUE, when writing 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 ID3v2 tag byupdate_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") to some"normalized"form. Takes two arguments: the MP3::Tag object, and the current value of the field.
The 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 is for this subroutine to translate a personal name field to a shortest"normalized"form.person_framesβ List of ID3v2 frames subject to normalization via"translate_person"handler; current default is"TEXT TCOM TXXX[TPE1] TPE1 TPE3 TOPE TOLY TMCL TIPL TENC TXXX[person-file-by]". Used byselect_id3v2_frame_by_descr(),frame_translate(),frames_translate().id3v2_missing_fatalβ If TRUE, interpolating ID3v2 frames (e.g., by"%{TCOM}") when the ID3v2 tag is missing is a fatal error. If false (default), in such cases interpolation results in an empty string.id3v2_recalculateβ If TRUE, interpolating the whole ID3v2 tag (by"%{ID3v2}") will recalculate the tag even if its contents is not modified.parse_minmatchβ May be 0, 1, or a list of"%"-escapes (matching any string) which should be matched non-greedily byparse()and friends. E.g., parsing'Adagio - Andante - Piano Sonata'via'%t - %l'gives different results for the settings 0 and 1; note that greediness of%ldoes not matter, thus the value of 1 is equivalent for the value of"t"for this particular pattern.id3v23_unsync_size_wβ Old experimental flag to test why ITunes refuses to handle unsyncronized tags (does not help, seeid3v23_unsync). The idea was that version 2.3 of the standard is not clear about frame size field, whether it is the size of the frame after unsyncronization, or not. We assume that this size is one before unsyncronization (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 unsyncronized (i.e., written as the standard requires it) tags; they may need this to be set to FALSE. Default: TRUE.
(Some details: by definition, MP3 files should contain combinations of bytes"FF F*"or"FF E*"only at the start of audio frames ("syncronization"points). ID3v2 standards take this into account, and supports storing raw tag data in a format which does not contain these combinations of bytes [via"unsyncronization"]. Itunes etc do not only emit broken MP3 files [which cause severe hiccups in players which do not know how to skip ID3v2 tags, as most settop DVD players], they also refuse to read ID3v2 tags written in a correct, unsyncronized, format.) (Note also that the issue of syncronization is also applicable to ID3v1 tags; however, since this data is near the end of the file, many players are able to recognize that the syncronization points in ID3v1 tag cannot start a valid frame, since there is not enough data to read; some other players would hiccup anyway if ID3v1 contains these combinations of bytes...)
encoded_v1_fitsβ If FALSE (default), data containing"high bit characters"is considered to not fit ID3v1 tag if one of the following conditions hold:"encode_encoding_v1"is set (so the resulting ID3v1 tag is not standard-complying, thus ambiguous without ID3v2), or"encode_encoding_v1"is not set, but"decode_encoding_v1"is set (thus read+write operation is not idempotent for ID3v1 tag).
With the default setting, these problems are resolved as far as (re)encoding of ID3v2 tag is non-ambiguous (which holds with the default settings for ID3v2 encoding).
decode_encoding_v1encode_encoding_v1decode_encoding_v2decode_encoding_filenamedecode_encoding_infdecode_encoding_cddb_filedecode_encoding_cuedecode_encoding_filesencode_encoding_files
okay bestie so in that exact order those are the encodings for "ID3v1", non-Unicode frames of "ID3v2", filenames, external files, .inf files, "CDDB" files, .cue files, and user-specified files β correspondingly. β¨ And a value of 0 means "latin1", periodt.
The default values for decode_encoding_* are set from the corresponding MP3TAG_DECODE_*_DEFAULT environment variable (here * stands for the uppercased last component of the name, iykyk π§); and if that variable isn't set, they come from MP3TAG_DECODE_DEFAULT. Likewise the default value for encode_encoding_v1 is set from MP3TAG_ENCODE_V1_DEFAULT or MP3TAG_ENCODE_DEFAULT; if neither is present, it falls back to the value for decode_encoding_v1. Same deal for encode_encoding_files. π
β οΈ Heads up:decode_encoding_v2has noencodepair. It can also be disabled per tag via the effects ofignore_trusted_encoding0_v2and the corresponding frameTXXX[trusted_encoding0_v2]in the tag. Also keep in mind that the ID3v1 standard requires the encoding to belatin1(so it doesn't store the encoding anywhere at all π); that genuinely does not make a lot of sense, and a lot of effort of this module is spent fixing this unfortunate flaw. See "Problems with ID3 format".
ignore_trusted_encoding0_v2
If FALSE (that's the default), and the frame TXXX[trusted_encoding0_v2] is set to TRUE, then the setting of decode_encoding_v2 is just... ignored. π
id3v2_set_trusted_encoding0
If TRUE (default), and frames are converted from the given decode_encoding_v2 to a standard-conforming encoding, a frame TXXX[trusted_encoding0_v2] with a TRUE value gets added. β¨
[The whole purpose is to make multi-step updates possible when decode_encoding_v2 is in the picture; with id3v2_set_trusted_encoding0 TRUE and ignore_trusted_encoding0_v2 FALSE (both default values, not me making this up), editing of tags can be idempotent. science π
]
id3v2_fix_encoding_on_write
If TRUE and decode_encoding_v2 is defined, the ID3v2 frames are converted to standard-conforming encodings on write. Default? FALSE. π«Ά
id3v2_fix_encoding_on_edit
If TRUE (default!) and decode_encoding_v2 is defined (and not disabled via a frame TXXX[trusted_encoding0_v2] and the setting ignore_trusted_encoding0_v2), a CYA action is performed when an edit may result in confusion. More precisely: adding an ID3v2 frame which is essentially affected by decode_encoding_v2 would convert other frames to a standard-conforming encoding (and would set TXXX[trusted_encoding0_v2] if required by id3v2_set_trusted_encoding0). π
Recall that added frames are always encoded in a standard-conformant way; the action above just avoids mixing non-standard-conformant frames with standard-conformant frames. Because bestie, such a mix could not be cleared up by setting decode_encoding_v2! π One more thing to keep in mind: this does not affect frames which contain characters above 0x255 β those frames are always written in Unicode, so they're not affected by decode_encoding_v2 at all. π
id3v2_frames_autofill
A hash of suggested ID3v2 frames to autogenerate, basing on extra information that's available. The keys are frame descriptors (like TXXX[cddb_id]), and the values say whether the ID3v2 tag should be created if it wasn't present. π
This variable is inspected by the method id3v2_frames_autofill, which is not called automatically when the tag is accessed β but scripts using the module may call it. π¦
The default is to force creation of the tag for the TXXX[MCDI-fulltoc] frame, and to not force creation for TXXX[cddb_id] and TXXX[cdindex_id].
local_cfg_file
Name of the configuration file read at startup by the method parse_cfg(); it's ~-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 β¨).
write_v24
If FALSE (default), writing of ID3v2.4 is prohibited (it's not fully supported β allow at your own risk, ngl π).
name_for_field_normalization
The 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 the operation of MP3::Tag. Applications using this module may add to this list so their own config can be done by the same means as the configuration of MP3::Tag. π«Ά
is_writable
Contains a boolean value, or a method name and argument list to call, to figure out whether the tag may be added to the file. Defaults to writable_by_extension(). βοΈ
writable_extensions
Contains a list of extensions (case insensitive) for which the tag may be added to the file. Current default is mp3 mp2 id3 tag ogg mpg mpeg mp4 aiff flac ape ram mpc (extracted from ExifTool docs; may be tuned later, so don't come for me π).
*Later there will be probably more things to configure. (future tea β)
β¨ the getter methods β¨
get_config
$opt_array = $mp3->get_config("item");
When object options are first time set or get, the global options are propagated into the object options. (So if global options are changed later, those changes are not inherited. sad but true π)
get_config1
$opt = $mp3->get_config1("item");
Similar to get_config(), but 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 which, 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, to simplify chaining of method calls. obsessed with a fluent API ngl π¦
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}). same scratch space, now with your stuff in it π
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). Otherwise it sets the frame, passing the specified @values to the add_frame() function of MP3::Tag::ID3v2. (And yeah β the old value is removed. out with the old π«Ά)
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 no ID3v2 tag is 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 is not present. ποΈ
is_id3v2_modified
$frame = $mp3->is_id3v2_modified();
Returns TRUE if the 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 β with undef meaning deletion π). For read-only access it returns empty if no ID3v2 tag is present, or if no frame is found.
β οΈ If new contents is specified, ALL the existing frames matching the specification are deleted. all of them. every single one. π
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, the list of wanted Descriptors, the 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 the long description of their 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 (things like "COMM(eng)[lyricist birthdate]"), appropriate for interpolation, or for select_id3v2_frame_by_descr(). π
select_id3v2_frame_by_descr
have_id3v2_frame_by_descr
Similar to select_id3v2_frame(), have_id3v2_frame(), except instead of the arguments $fname, $descrs, $langs they take one single string of the form
NAME(langs)[descr]
Both the (langs) and [descr] parts may be omitted; langs should contain a comma-separated list of the needed languages. The semantic is similar to MP3::Tag::ID3v2::frame_select_by_descr_simpler. π
It's allowed to have NAME of the form FRAMnn; the nn-th frame with name FRAM is chosen (-1-based: the first frame is FRAM, the second FRAM00, the third FRAM01 etc; for a more user-friendly scheme, use langs of the form #NNN, with NNN 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 in 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
π heads up bestie: when you useselect_id3v2_frame_by_descr()to modify stuff, ALL the frames it finds get deleted before the shiny new one gets added. No take-backsies. For the gory details, go peek at"frame_select"in MP3::Tag::ID3v2.
π frame_translate
$mp3->frame_translate('TCOM'); # Normalize TCOM ID3v2 frame
So this one assumes the frame's value is a person's name, and then it normalizes that value using personal-name-normalization logic (that's the "translate_person" configuration value doing the work β¨).
The frame itself gets updated β but heads up, the tag is not written back to the file. And lowkey important: the frame has to be in the list of personal-names frames (the "person_frames" configuration value), or else it's a no-go.
π¦ frames_translate
Basically frame_translate()'s louder sibling β it updates all the frames listed in the "person_frames" configuration value. Group effort, slay π
.
πΈ copy_id3v2_frames($from, $to, $overwrite, [$keep_flags, $f_ids])
Copies the frames you specify between the "MP3::Tag" objects $from and $to. Unless you pass $keep_flags, the copied frames get their flags cleared. If the array reference $f_ids isn't given, then all the frames get considered (except "GRID" and "TLEN" β not invited to the party) β 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 exceptions.
Now for the $overwrite tea β:
- If
$overwriteis'delete', frames in$towith the same descriptors (as returned byget_frame_descr()) get deleted first, then all the specified frames are copied. - If
$overwriteis FALSE, only the frames whose descriptors aren't already chilling in$toget copied.
π¨ ngl, if one of those two conditions isn't met, the result may not be conformant to standards. You've been warned, bestie.
Returns the count of copied frames. π
π§ _Data_to_MIME
Internal method that extracts the MIME type from a string of image-file content. Returns "application/octet-stream" for data it doesn't recognize β unless you gave that extra TRUE argument, in which case, different story.
$format = $id3->_Data_to_MIME($data);
Right now it only inspects the first 4 bytes of the string. Baby steps π.
π 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. It's giving glow-up β¨.
π id3v2_frames_autofill
$mp3->id3v2_frames_autofill($force);
Generates the missing tags from the list specified in the "id3v2_frames_autofill" configuration variable. These tags have to come from a short list this method actually knows how to deal with:
TXXX[MCDI-fulltoc]β filled from the fileaudio_cd.tocin the directory of the audio file. Create this file with:
readcd -fulltoc dev=0,1,0 -f=audio_cd >& nul
(modify the dev β and the redirection per your shell π).
TXXX[cddb_id]TXXX[cdindex_id]β filled from the result of the corresponding method (which may extract from.inforcddbfiles).
Existing frames are not modified unless you specify the $force option; and when $force is true, the ID3v2 tag will be created even if it wasn't there to begin with. Manifesting a whole tag into existence, iconic π
.
π«Ά interpolate
$string = $mp3->interpolate($pattern)
Interpolates the "%"-escapes in $pattern using the info from the $mp3 tags. The escape syntax is similar to sprintf():
% [ [FLAGS] MINWIDTH] [.MAXWIDTH] ESCAPE
The only recognized FLAGS are - (to denote left-alignment inside a MINWIDTH-wide field), ' ' (SPACE), and 0 (denoting the fill character to use) β plus an arbitrary character in parentheses (which becomes the fill character). MINWIDTH and MAXWIDTH should be numbers, bestie.
The short ESCAPEs get replaced by:
%β 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 extensionvβ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βframeshβheight(these 3 are for image files;Image::SizeorImage::ExifDatarequired)wβ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_depthaCβ 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, like"%{SML}"or"%.5{aR}". Don't forget the curly braces, bestie, or it's not gonna hit.
Additional multi-char escapes are interpreted like this:
- Names of ID3v2 frames are replaced by their text values (empty for missing frames).
- Strings
"n1"and"n2"are replaced by "pure track number" and "max track number" β this lets both formats"N1"and"N1/N2"of"track"work, the latter meaning track N1 of N2. Use"n0"to pad"n1"with leading0to the width of"n2"(or to 2, in the absence of n2). Same deal for"m1","m2"but with disk (media) number instead of track number; use"mA"to encode"m1"as a letter (seedisk_alphanum()). - Strings
"ID3v1"and"ID3v2"are replaced by the whole ID3v1/2 tag (interpolation of"ID3v2"for an unmodified tag is subject to the"id3v2_recalculate"configuration variable). Heads up: these may work as conditionals too, with":"π. - Strings of the form
"FRAM(list,of,languages)[description]"get replaced by the first FRAM frame with the descriptor"description"in 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"β e.g."#4"means the 4th FRAM frame, or FRAM04. An empty string for the language means any language. This works as a condition for conditional interpolation too, bestie.- Any one of the list of languages and the description can be omitted β that means either the frame FRAM has 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.
- Several descriptors of the
"FRAM(list,of,languages)[description]"form discussed above can be combined together with"&"; the non-empty expansions get joined together with the value of the configuration variable"ampersand_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"method"(with the given arguments) in one of the specified known subpackages (e.g. for"Inf","MP3::Tag::Inf"gets used). Arbitrary numbers of arguments are supported. Instead of the long name"method"you can use its standard shortcut (e.g."t"for"title"). For example:
$mp3->interpolate('%{t(ID3v1,Cue)}')
returns the title from the ID3v1 tag, or (if it's not there) from a cue sheet. You can use this in conditionals etc. as well π .
"d"NUMBER is replaced by the NUMBER-th component of the directory name (with0corresponding to the last component)."D"NUMBER is replaced by the directory name with NUMBER components stripped."U"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:"get treated similarly, but with an inverted test. - 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 similarly to ID3v2 conditionals, but 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
"|"or LETTER"||". - For strings of the form
"nmP[VALUE]"or"shP[VALUE]", VALUE is interpolated, then normalized or shortened as a personal name (according to the"translate_person"or"short_person"configuration setting). "composer"or"performer"is replaced by the result of calling the corresponding method.framesβ gets swapped for a space-separated list of the long names of ID3v2 frames (peepid3v2_frame_descriptors()). Wanna use a different separator? Put it after a slash, like%{frames/, }, where the separator isCOMMA SPACE. π_out_frames[QQPRE//QQPOST]β gets replaced by a verbose listing of frames."simple"frames come out one-per-line (with the value wrapped inQQPREandQQPOST); fields of other frames also come out one-per-line. If you omit the leading_, then__binary_DATA__replaces the value of binary fields. β¨ID3v2-size,ID3v2-pad, andID3v2-strippedβ these get replaced by the size of the ID3v2 tag in bytes, the amount of0-padding at the end of the tag (not counting one extra0byte 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). π«ΆID3v2-modifiedβ becomes'modified'if ID3v2 is present and is modified in memory; otherwise it becomes an empty string. π¦- For strings shaped like
I(FLAGS)VALUE, VALUE gets interpolated with the flags in FLAGS (seeinterpolate_with_flags). If FLAGS doesn't containi, VALUE should have{}and\backwacked. π - For strings shaped like
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. If both are given, the fill character should preceed the -. 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.
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->interpolatefβ interpret (the result) as filename, read from fileFβ if file does not exist, it is not an errorBβ read is performed in binary mode (otherwise in text mode, modified per'decode_encoding_files'configuration variable)lβ split result per'parse_split'configuration variablenβ asl, using the track-number-th element (1-based) in the resultIβ interpolate (again) via$mp3->interpolatebβ 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. π
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. π«Ά
the filename squad: 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. π
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, this whole lil' squad of methods hands you back info about what's actually inside the MP3 file β¨ Heads up though: if that info isn't cached in ID3v2 tags (which β fun fact β isn't implemented yet π), then using any of these 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 this module's get_mp3info() method β specifically, the info about frame number and frame length is only approximate. Not exact. Vibes-based. π
A few deets so you don't get caught out:
vbr_scale()comes from the VBR header.total_secs()isn't necessarily an integer, buttotal_secs_int()andtotal_secs_trunc()are β the first one is rounded, the second one is truncated.time_mm_ss()has the format"MM:SS".- the
*_YNflavors return the value as a string,YesorNo. mpeg_layer_roman()returns the value as a roman numeral (iconic of it honestly).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 single simple letter, or a string in braces that's appropriate to slap right after "%" in an interpolated string. A format descriptor can be followed by a literal string that gets tacked on as a suffix, and it can also be preceded by a question mark β which means "only print this part of the format if it's actually needed, bestie."
Leftover minutes and seconds get formatted 0-padded to width 2 if they're preceded by more coarse units. Same energy for leftover milliseconds: printed with a leading dot, 0-padded to width 3.
Two examples of @formats that are genuinely useful:
qw(?H: ?{mL}: {SML})
qw(?Hh ?{mL}m {SL} ?{ML})
Both of these print hours, minutes, and milliseconds only if needed. The second one uses 3-digit format after a point; the first one does not print the trailing 0s of milliseconds. The first one uses ":" as the separator between hours and minutes; the second one goes with "h m". Pick your fighter π₯
Optionally, the first element of the array may be of the form "=>U", where "U" is one of "h m s". In that case, the duration gets rounded to the closest hour, minute, or second before processing. (Like, for example, 1.7sec would print as 1 with the @formats above β but it 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)
Same as can_write(), but die()s on non-writable files with a meaningful error message ($mess gets 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 β and for the v2 one, only if the in-memory copy contains any data, or $data doesn't fit the ID3v1 restrictions, or the $force2 argument is given β using the info about title, artist, album, year, comment, track, and 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'). Fields that are marked as coming from ID3v1 or ID3v2 tags are not updated when written to the same tag. (Self-aware king behavior tbh π)
If $data is not defined or is missing, autoinfo('from') gets called to obtain the data. Returns the object reference itself, so you can chain method calls like a menace β¨
This is probably the simplest way to set data in the tags: just populate $data and call this method β no further tinkering with subtags needed. So easy. So slay.
π¦ 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 the configuration variable "local_cfg_file", which is "~"-substituted. Empty lines and lines starting with "#" are ignored. The remaining lines should have the format "varname=value"; leading and trailing whitespace gets stripped; and there may be several lines with the same "varname" β that's what sets list-valued variables, iykyk π
π ENVIRONMENT π
Some defaults for how this module operates (and/or for scripts distributed with this module) come straight from the environment π«Ά Assumed encodings (either 0 or an 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
and for write access:
MP3TAG_ENCODE_V1_DEFAULT MP3TAG_ENCODE_FILES_DEFAULT
(if those aren't set, they default to the corresponding "DECODE" options).
Defaults for all of the above:
MP3TAG_DECODE_DEFAULT MP3TAG_ENCODE_DEFAULT
(if the second one isn't set, the value of the first one gets used). A value of 0 for a more specific variable cancels the effect of the less specific variables. Casual hierarchy. We love to see it.
If the "LANG" environment variable indicates "UTF-8" encoding, then the "FILES" flavors default to "utf8" β unless that effect is already achieved by the "${^UNICODE}" variable. You can disable this by setting "MP3TAG_DECODE_FILES_DEFAULT_RESET" true in the environment (and 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, you can use the config()/get_config() methods to change/access these settings. See "encode_encoding_*" and "encode_decoding_*" in the documentation of the config method. (Also note that the "FILES" variant governs files read/written in non-binary mode by "ParseData" in the MP3 module, as well as the reading of control files of some scripts that use this module, such as typeset_audio_dir.)
π« EXAMPLE π«
Say the 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, it's widely used anyway), and you want "ID3v1" fields to be in that same encoding β but you want "ID3v2" to 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 get the effect you want for both reading and writing MP3 tags. Two birds, one env var π¦π¦
Additionally, the following (unsupported! β οΈ) variables are currently recognized by the ID3v2 code:
MP3TAG_DECODE_UNICODE MP3TAG_DECODE_UTF8
MP3TAG_DECODE_UNICODE (default 1) enables decoding; the target of the decoding is determined by MP3TAG_DECODE_UTF8: if 0, decoded values are byte-encoded UTF-8 (every Perl character contains a byte of a UTF-8 encoded string); otherwise (the default) it's a native Perl Unicode string.
If "MP3TAG_SKIP_LOCAL" is true, local customization files are not loaded. Bye bestie π
π CUSTOMIZATION π
Many aspects of how this module operates are subject to certain subtle choices. A lot of effort went into making these choices customizable, by setting global or per-object configuration variables. They really said "you WILL be able to tweak this" and honestly? Respect π
A certain degree of customization of the global configuration variables is available via the environment variables. On top of that, at startup the local customization file ~/.mp3tagprc is read, and defaults get set accordingly.
And 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) gets loaded directly; if sequential loading is what you want, the first thing a customization module should do is call:
MP3::Tag->load_parents()
The customization modules get an opportunity to change global configuration variables on load. And for extra 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's 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. Canonical queen behavior π
To simplify debugging of local customization, it may be switched off completely by setting MP3TAG_SKIP_LOCAL to TRUE (in the environment).
For example, putting:
id3v23_unsync = 0
into ~/.mp3tagprc will produce broken ID3v2 tags (but, like, the ones required by ITunes). So yeah β do that on purpose or not at all π
π¬ EXAMPLE SCRIPTS π¬
Okay so some example scripts come with this module β either installed, or chilling in the examples directory in the distribution. They either use this module, or they provide data that this module understands. Iconic little ecosystem, honestly π
mp3info2β does command line manipulation of audio tags (and more!);audio_renameβ renames audio files according to associated tags (and more!);typeset_mp3_dirβ writes LaTeX files suitable for CD covers and normal-size sheet descriptions of a hierarchy of audio files;mp3_total_timeβ calculates total duration of audio files;eat_wav_mp3_headerβ removes 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
and run it 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); it assumes that the files are a rip from a CD, and that alphabetical sort gives the track order. This only works heuristically, since the quantization of duration of MP3 files and of CD tracks is so different. Run it 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 it similar to:
inf_2fake_cddb | cddb2cddb > cddb.out
cddb2cddbβ reads a (header of) CDDB file fromSTDIN, and outputs (onSTDOUT) 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.
And yes β the last four do not use these modules! Noted, bestie π
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 absolute biggest problem with the ID3 format is that the first versions of this format were absolutely broken β underspecified, no cap. 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). It's giving "we fixed it" but the fix is lowkey haunted π
So what's wrong 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 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 the impossibility of distinguishing 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). Big yikes. (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 an ID3v2 tag even if it is stored as Unicode strings.)
This is why this module provides what some may consider only lukewarm support for the 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). Like, it's a whole trust-chain situation and the chain is made of vibes and prayers π
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 an 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 the 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 the TPE1 frame) (the second example). Obsessed with a fallback chain that actually respects the chaos π«Ά
π FILES π
There are many files with special meaning to this module and its dependent modules. Bestie, this is the file lore β¨
*.inf
Files with extension .inf and the same basename as the audio file are read by module MP3::Tag::Inf, and the extracted data is merged into the information flow according to configuration variable autoinfo.
It is assumed that these files are compatible in format to the files written by the program cdda2wav.
audio.cddb cddb.out cddb.in
Files named audio.cddb, cddb.out, and cddb.in in the same directory as the audio file are read by module MP3::Tag::CDDB_File, and the extracted data is merged into the information flow according to configuration variable autoinfo.
(In fact, the list may be customized by configuration variable cddb_files.)
audio_cd.toc
audio_cd.toc in the same directory as the audio file may be read by the method id3v2_frames_autofill() (should be called explicitly) to fill the TXXX[MCDI-fulltoc] frame. Depends on contents of configuration variable id3v2_frames_autofill.
~/.mp3tagprc
By default, this file is read on startup (may be customized by overriding the method parse_cfg()). By default, the name of the file is in the configuration variable local_cfg_file.
π SEE ALSO π
MP3::Tag::ID3v1, MP3::Tag::ID3v2, MP3::Tag::File, MP3::Tag::ParseData, MP3::Tag::Inf, MP3::Tag::CDDB_File, MP3::Tag::Cue, MP3::Tag::ImageExifTool, MP3::Tag::ImageSize, MP3::Tag::LastResort, mp3info2, typeset_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
That's the whole page, bestie β source/version perl v5.42.3, dated 2022-11-25 β mwah πβ¨
π¦ where this page comes from
- nixos 26.05: perl5.42.3-MP3-Tag 1.16
- nixpkgs unstable: perl5.42.3-MP3-Tag 1.16
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms