### Gio Example Implementation for File-like Object Source: https://github.com/quodlibet/mutagen/blob/main/docs/user/filelike.md This example demonstrates using PyGObject and Gio to create a file-like object for Mutagen. Ensure the 'giofile' library is installed. ```python import mutagen import giofile from gi.repository import Gio gio_file = Gio.File.new_for_uri( "http://people.xiph.org/~giles/2012/opus/ehren-paper_lights-96.opus") cancellable = Gio.Cancellable.new() with giofile.open(gio_file, "rb", cancellable=cancellable) as gfile: print(mutagen.File(gfile).pprint()) ``` -------------------------------- ### Install Mutagen using apt-get Source: https://github.com/quodlibet/mutagen/blob/main/docs/index.md Install the Mutagen library using the apt-get package manager on Debian-based systems. ```default sudo apt-get install python3-mutagen ``` -------------------------------- ### Install Mutagen using pip Source: https://github.com/quodlibet/mutagen/blob/main/docs/index.md Install the Mutagen library using pip for Python 3.10+. ```default python3 -m pip install mutagen ``` -------------------------------- ### Example of UrlFrame creation Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/id3_frames.md Illustrates the creation of a UrlFrame, which stores a single URL string. The documentation notes that URLs in MP3s should ideally be restricted to ASCII for compatibility. ```python frame = UrlFrame(url='http://example.com') ``` -------------------------------- ### Add Multiple Cover Images with Unique HashKeys Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/id3_frames.md When adding multiple APIC frames, ensure each has a unique HashKey. This example demonstrates using the `salt` attribute to differentiate frames with potentially identical descriptions. ```python import mimetypes from mutagen.id3 import ID3, APIC, PictureType tags = ID3('example.mp3') image_filenames = ['example.jpeg', 'example.png'] for image_filename in image_filenames: image_mime_type = mimetypes.guess_file_type(image_filename)[0] with open(image_filename, 'rb') as f: image_data = f.read() apic = APIC( mime=image_mime_type, type=PictureType.COVER_FRONT, data=image_data ) while apic.HashKey in tags: apic.salt += ' ' tags.add(apic) ``` -------------------------------- ### Get MP3 Length and Bitrate Source: https://github.com/quodlibet/mutagen/blob/main/docs/user/gettingstarted.md Load an MP3 file and retrieve its length in seconds and bitrate. Use this to get audio playback information. ```python from mutagen.mp3 import MP3 audio = MP3("example.mp3") print(audio.info.length) print(audio.info.bitrate) ``` -------------------------------- ### Example of PairedTextFrame usage Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/id3_frames.md Demonstrates how to create and use a PairedTextFrame, which stores pairs of strings. The 'people' attribute holds these pairs, and the frame supports different text encodings. ```python frame = PairedTextFrame(encoding=Encoding.UTF8, people=[['trumpet', 'Miles Davis'], ['bass', 'Paul Chambers']]) ``` -------------------------------- ### Get All Frames by Key Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/id3.md Retrieves all frames matching a given key. Useful for accessing multiple frames of the same type or frames with specific descriptions. ```default id3.getall('TIT2') == [id3['TIT2']] id3.getall('TTTT') == [] id3.getall('TXXX') == [TXXX(desc='woo', text='bar'), TXXX(desc='baz', text='quuuux'), ...] getall('COMM:MusicMatch') getall('TXXX:QuodLibet:') ``` -------------------------------- ### Control Padding with PaddingInfo Callback Source: https://context7.com/quodlibet/mutagen/llms.txt Illustrates how to control file padding during save operations using a callback function that receives a PaddingInfo object. This can optimize file rewrites when metadata changes. Examples include no padding, default, preserving, and capped padding. ```python from mutagen.mp3 import MP3 from mutagen.flac import FLAC from mutagen import PaddingInfo # No padding at all (smallest file, full rewrite if tags grow) def no_padding(info: PaddingInfo) -> int: return 0 # Default mutagen strategy (balances file size vs rewrite cost) def default_padding(info: PaddingInfo) -> int: return info.get_default_padding() # Keep existing padding but never add more def preserve_padding(info: PaddingInfo) -> int: return max(info.padding, 0) # Cap padding at 8 KB def capped_padding(info: PaddingInfo) -> int: return min(info.get_default_padding(), 8192) # Apply to MP3 (ID3 tags) mp3 = MP3("track.mp3") mp3["TIT2"] = "New Title" # via ID3 frame dict directly mp3.save(padding=capped_padding) # Apply to FLAC flac = FLAC("track.flac") flac["title"] = [u"New Title"] flac.save(padding=no_padding) ``` -------------------------------- ### Example of TextFrame manipulation Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/id3_frames.md Illustrates common operations on TextFrames, such as appending and extending the list of strings. TextFrames support various encodings, with UTF-8 being recommended for simplicity. ```python frame = TextFrame() frame.append('Hello') frame.extend(['World', '!']) print(frame.text) ``` -------------------------------- ### APEv2 Case-Sensitive Key Example (Mutagen >= 1.8) Source: https://github.com/quodlibet/mutagen/blob/main/docs/user/apev2.md Illustrates case-sensitive key comparison for APEv2 tags in Mutagen version 1.8 and above. Direct key lookups remain case-insensitive. ```python print "foo" in tag ``` -------------------------------- ### Example of NumericTextFrame usage Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/id3_frames.md Demonstrates how to retrieve the numerical value from a NumericTextFrame using the unary plus operator. This is useful for frames containing single numerical values. ```python frame = TLEN('12345') length = +frame # length == 12345 ``` -------------------------------- ### APEv2 Case-Insensitive Key Example (Mutagen < 1.8) Source: https://github.com/quodlibet/mutagen/blob/main/docs/user/apev2.md Demonstrates case-insensitive key comparison for APEv2 tags in Mutagen versions prior to 1.8. Note that this behavior has changed in newer versions. ```python tag = APEv2() tag["Foo"] = "Bar" print "foo" in tag.keys() ``` -------------------------------- ### Example of NumericPartTextFrame usage Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/id3_frames.md Shows how to extract the numerical value from a NumericPartTextFrame, which represents values like 'track X of Y'. Unary plus operator can be used to get the first numerical part. ```python frame = TRCK('4/15') track = +frame # track == 4 ``` -------------------------------- ### Use EasyID3 with MP3 Files Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/id3.md Demonstrates how to use EasyID3 as a wrapper for mutagen.mp3.MP3 files for easier tag access. ```python from mutagen.mp3 import EasyMP3 as MP3 MP3(filename) ``` -------------------------------- ### Metadata Class Initialization Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/base.md Instantiate the Metadata class, optionally providing a filething to load existing tags or None to create an empty instance. ```python metadata_instance = mutagen.Metadata(filething=None, **kwargs) ``` -------------------------------- ### mutagen.id3.TKEY Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/id3_frames.md Starting Key frame. Inherits from TextFrame and has attributes for encoding and text. ```APIDOC ## class mutagen.id3.TKEY Bases: [`TextFrame`](#mutagen.id3.TextFrame) Starting Key ``` -------------------------------- ### Instantiate ID3 Metadata Source: https://github.com/quodlibet/mutagen/blob/main/docs/user/classes.md Demonstrates how to instantiate an ID3 Metadata object from an MP3 file. This is used for tagging formats not dependent on a container. ```python >>> from mutagen.id3 import ID3 >>> m = ID3("08. Firestarter.mp3") >>> type(m) >>> ``` -------------------------------- ### StreamInfo Class pprint Method Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/base.md Use the pprint method on a StreamInfo instance to get a formatted string of stream information. ```python stream_info_instance.pprint() ``` -------------------------------- ### Tags Class pprint Method Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/base.md Use the pprint method on a Tags instance to get a formatted string of tag information. ```python tags_instance.pprint() ``` -------------------------------- ### Import and Open File Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/base.md Import the necessary format module and open a file to access its metadata. The metadata object behaves like a dictionary. ```python import mutagen.[format] metadata = mutagen.[format].Open(filename) ``` -------------------------------- ### FileType mime Property Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/base.md Access the mime property of a FileType instance to get a list of MIME types associated with the file. ```python mime_types = file_type_instance.mime ``` -------------------------------- ### Load Audio from File-like Objects Source: https://context7.com/quodlibet/mutagen/llms.txt Shows how to load audio metadata from file-like objects (e.g., BytesIO for in-memory data) instead of just filenames. This requires the object to implement read(), seek(), and tell() for loading, and write(), flush(), truncate() for saving. ```python from io import BytesIO from mutagen.mp3 import MP3 from mutagen.flac import FLAC import mutagen # Load from BytesIO (in-memory) with open("track.mp3", "rb") as f: data = f.read() buf = BytesIO(data) audio = MP3(buf) print(f"Length: {audio.info.length:.2f}s") # Auto-detect format from file-like object buf.seek(0) generic = mutagen.File(buf) print(generic.info.pprint()) ``` -------------------------------- ### Registering a User-Defined Text Frame Key in EasyID3 Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/id3.md Demonstrates registering a key for user-defined text frames (TXXX) in EasyID3, allowing for custom tags with descriptions. ```python EasyID3.RegisterTXXXKey('barcode', 'BARCODE'). ``` -------------------------------- ### FileType Tags Attribute Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/base.md Access the Tags object from a FileType instance to get the metadata tags. This can be None if no tags are present. ```python tags = file_type_instance.tags ``` -------------------------------- ### FileType Class Initialization Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/base.md Instantiate the FileType class to automatically detect and open an audio file. It can optionally take a sequence of FileType implementations and a boolean to enable easy wrappers. ```python file_type_instance = mutagen.File(filething, options=None, easy=False) ``` -------------------------------- ### Clone Mutagen Git Repository Source: https://github.com/quodlibet/mutagen/blob/main/docs/index.md Clone the Mutagen source code repository from GitHub to get the latest version or contribute. ```default $ git clone https://github.com/quodlibet/mutagen.git ``` -------------------------------- ### FileType Info Attribute Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/base.md Access the StreamInfo object from a FileType instance to get details like length, bitrate, and sample rate. ```python stream_info = file_type_instance.info ``` -------------------------------- ### Create a FLAC Picture Object Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/flac.md Instantiate a Picture object and set its properties manually to create a picture for a FLAC file. Ensure the file is opened in binary read mode. ```python pic = Picture() with open("Folder.jpg", "rb") as f: pic.data = f.read() pic.type = id3.PictureType.COVER_FRONT pic.mime = u"image/jpeg" pic.width = 500 pic.height = 500 pic.depth = 16 # color depth ``` -------------------------------- ### FileType pprint Method Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/base.md Use the pprint method on a FileType instance to get a formatted string of stream information and comment key-value pairs. ```python print(file_type_instance.pprint()) ``` -------------------------------- ### Load Audio File and Display Info Source: https://github.com/quodlibet/mutagen/blob/main/docs/user/gettingstarted.md Load an audio file and display its metadata and information. Use this to inspect audio file tags and properties. ```python >>> import mutagen >>> mutagen.File("11. The Way It Is.ogg") {'album': [u'Always Outnumbered, Never Outgunned'], 'title': [u'The Way It Is'], 'artist': [u'The Prodigy'], 'tracktotal': [u'12'], 'albumartist': [u'The Prodigy'],'date': [u'2004'], 'tracknumber': [u'11'], >>> _.info.pprint() u'Ogg Vorbis, 346.43 seconds, 499821 bps' >>> ``` -------------------------------- ### mutagen.mp4.MP4Chapters Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/mp4.md Represents MPEG-4 Chapter information, supporting the ‘moov.udta.chpl’ box. It is a sequence of Chapter objects, each with a start time and title. ```APIDOC ## class mutagen.mp4.MP4Chapters ### Description MPEG-4 Chapter information. Supports the ‘moov.udta.chpl’ box. A sequence of Chapter objects with the following members: : start (`float`): position from the start of the file in seconds title (`str`): title of the chapter ``` -------------------------------- ### Open and Interact with Any Audio File using mutagen.File() Source: https://context7.com/quodlibet/mutagen/llms.txt Use `mutagen.File()` to automatically detect and open any supported audio file. Access tags like a dictionary and modify stream information. Set `easy=True` for a simplified interface. ```python import mutagen from mutagen import MutagenError # Open any supported audio file — format is auto-detected try: audio = mutagen.File("track.mp3") if audio is None: print("Unknown or unsupported format") else: # Dictionary-like access to tags (values are always lists) print(audio["artist"]) print(audio["title"]) print(audio["album"]) # Stream information print(audio.info.length) print(audio.info.bitrate) print(audio.info.pprint()) # Modify and save audio["comment"] = [u"Tagged with Mutagen"] audio.save() except MutagenError as e: print(f"Error: {e}") # Use easy=True for a simplified Vorbis-style key interface on MP3/MP4 easy_audio = mutagen.File("track.mp3", easy=True) easy_audio["title"] = [u"New Title"] easy_audio.save() ``` -------------------------------- ### ASF Tags Dictionary Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/asf.md Interact with ASF tags as a dictionary-like object. You can access keys, convert to a dictionary, or get a pretty-printed string representation of all tags. ```python from mutagen.asf import ASF audio = ASF(filething) keys = audio.tags.keys() as_dict = audio.tags.as_dict() pprint_tags = audio.tags.pprint() ``` -------------------------------- ### Instantiate OggVorbis FileType Source: https://github.com/quodlibet/mutagen/blob/main/docs/user/classes.md Demonstrates how to instantiate an OggVorbis FileType object from a file path. This is the primary way to interact with Ogg Vorbis files in Mutagen. ```python >>> from mutagen.oggvorbis import OggVorbis >>> f = OggVorbis("11. The Way It Is.ogg") >>> type(f) >>> ``` -------------------------------- ### Registering a Simple Text Key in EasyID3 Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/id3.md Shows how to register a new key in EasyID3 that directly maps to an ID3 frame ID, simplifying text tag management. ```python EasyID3.RegisterTextKey("title", "TIT2") ``` -------------------------------- ### Musepack Methods Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/index.md Methods for interacting with Musepack audio files. ```APIDOC ## Musepack.info ### Description Retrieves information about the Musepack file. ### Method N/A (Property access) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (200) - **info** (object) - Information about the Musepack file. ### Response Example None ``` ```APIDOC ## Musepack.score() ### Description Calculates a score for the Musepack file. ### Method N/A (Method call) ### Endpoint N/A ### Parameters None ### Request Example None ### Response None ### Response Example None ``` -------------------------------- ### EasyID3 Class Methods Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/id3.md Methods for registering custom key mappings and handling ID3 frames. ```APIDOC ## Class Methods for EasyID3 #### RegisterKey(key, getter=None, setter=None, deleter=None, lister=None) Register a new key mapping. A key mapping is four functions, a getter, setter, deleter, and lister. The key may be either a string or a glob pattern. The getter, deleted, and lister receive an ID3 instance and the requested key name. The setter also receives the desired value, which will be a list of strings. The getter, setter, and deleter are used to implement __getitem__, __setitem__, and __delitem__. The lister is used to implement keys(). It should return a list of keys that are actually in the ID3 instance, provided by its associated getter. #### RegisterTextKey(key, frameid) Register a text key. If the key you need to register is a simple one-to-one mapping of ID3 frame name to EasyID3 key, then you can use this function: ```python EasyID3.RegisterTextKey("title", "TIT2") ``` #### RegisterTXXXKey(key, desc) Register a user-defined text frame key. Some ID3 tags are stored in TXXX frames, which allow a freeform ‘description’ which acts as a subkey, e.g. TXXX:BARCODE.: ```python EasyID3.RegisterTXXXKey('barcode', 'BARCODE'). ``` ``` -------------------------------- ### Set ASF Tags with Typed Attribute Objects Source: https://context7.com/quodlibet/mutagen/llms.txt Demonstrates setting various ASF tags using typed attribute objects like ASFUnicodeAttribute and ASFWordAttribute. Ensure the audio object is properly initialized before saving. ```python audio.tags["Title"] = [ASFUnicodeAttribute(u"Song Title")] audio.tags["Author"] = [ASFUnicodeAttribute(u"Artist Name")] audio.tags["WM/AlbumTitle"]= [ASFUnicodeAttribute(u"Album Name")] audio.tags["WM/Year"] = [ASFUnicodeAttribute(u"2024")] audio.tags["WM/TrackNumber"]= [ASFWordAttribute(5)] audio.tags["WM/BeatsPerMinute"] = [ASFWordAttribute(120)] audio.save() ``` -------------------------------- ### OptimFROG Class Methods Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/index.md Methods available for the OptimFROG audio format handler. ```APIDOC ## OptimFROG.info ### Description Retrieves information about the OptimFROG file. ### Method N/A (Attribute Access) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (N/A) - **info** (OptimFROGInfo) - An object containing detailed information about the OptimFROG file. #### Response Example None ## OptimFROG.tags ### Description Retrieves the tags associated with the OptimFROG file. ### Method N/A (Attribute Access) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (N/A) - **tags** (VCommentDict) - An object representing the Vorbis comment tags. #### Response Example None ## OptimFROG.score() ### Description Calculates a score for the OptimFROG file. ### Method N/A (Method Call) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (N/A) - **score** (float) - The calculated score. #### Response Example None ``` -------------------------------- ### Get All ID3 Frames of a Type Source: https://github.com/quodlibet/mutagen/blob/main/docs/user/id3.md To retrieve all frames of a specific type, use the getall() method. This is useful when multiple frames of the same type might exist, like TXXX frames. ```python for frame in mutagen.File("01. On The Road Again.mp3").tags.getall("TXXX"): frame ``` -------------------------------- ### OggTheora Methods Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/index.md Methods for interacting with Ogg Theora video files. ```APIDOC ## OggTheora.info ### Description Retrieves information about the Ogg Theora file. ### Method N/A (Property access) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (200) - **info** (object) - Information about the Ogg Theora file. ### Response Example None ``` ```APIDOC ## OggTheora.tags ### Description Accesses the tags associated with the Ogg Theora file. ### Method N/A (Property access) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (200) - **tags** (object) - The tags object for the Ogg Theora file. ### Response Example None ``` ```APIDOC ## OggTheora.score() ### Description Calculates a score for the Ogg Theora file. ### Method N/A (Method call) ### Endpoint N/A ### Parameters None ### Request Example None ### Response None ### Response Example None ``` -------------------------------- ### Handle MutagenError Exception Source: https://github.com/quodlibet/mutagen/blob/main/docs/user/classes.md Provides an example of how to catch MutagenError, the base exception class for all custom exceptions in Mutagen. This is useful for robust error handling when loading audio files. ```python from mutagen import MutagenError try: f = OggVorbis("11. The Way It Is.ogg") except MutagenError: print("Loading failed :(") ``` -------------------------------- ### Create ASFQWordAttribute Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/asf.md Instantiate an ASFQWordAttribute with an integer value. This represents a QWORD attribute within an ASF file. ```python from mutagen.asf import ASFQWordAttribute qword_attr = ASFQWordAttribute(42) ``` -------------------------------- ### ASFInfo.pprint() Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/index.md Pretty-prints the information contained within an ASFInfo object. ```APIDOC ## ASFInfo.pprint() ### Description Provides a human-readable, formatted string representation of the ASF file's information, including details like length, sample rate, bitrate, and codec information. ### Method This is a method of the ASFInfo class. ### Endpoint N/A (This is a library method, not an HTTP endpoint) ### Parameters None explicitly documented in the provided text. ### Request Example ```python # Assuming 'info' is an instance of mutagen.asf.ASFInfo print(info.pprint()) ``` ### Response - **formatted_info** (str) - A multi-line string containing the formatted file information. ``` -------------------------------- ### MP3 with EasyID3 Source: https://github.com/quodlibet/mutagen/blob/main/docs/user/id3.md Configures the MP3 class to use EasyID3 as its default ID3 handler for easier tag manipulation. This requires importing both classes. ```python from mutagen.easyid3 import EasyID3 from mutagen.mp3 import MP3 audio = MP3("example.mp3", ID3=EasyID3) audio.pprint() ``` -------------------------------- ### ASF Attribute Classes Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/asf.md Classes representing various attribute types within ASF files, including generic, GUID, WORD, DWORD, QWORD, Bool, Byte Array, and Unicode string attributes. ```APIDOC ## class mutagen.asf.ASFBaseAttribute Generic attribute. #### language *= None* Language #### stream *= None* Stream #### value *= None* The Python value of this attribute (type depends on the class) ## class mutagen.asf.ASFGUIDAttribute(value) GUID attribute. * **Bases:** [`ASFBaseAttribute`](#mutagen.asf.ASFBaseAttribute) ## class mutagen.asf.ASFWordAttribute(value) WORD attribute. ```default ASFWordAttribute(42) ``` * **Bases:** [`ASFBaseAttribute`](#mutagen.asf.ASFBaseAttribute) ## class mutagen.asf.ASFDWordAttribute(value) DWORD attribute. ```default ASFDWordAttribute(42) ``` * **Bases:** [`ASFBaseAttribute`](#mutagen.asf.ASFBaseAttribute) ## class mutagen.asf.ASFQWordAttribute(value) QWORD attribute. ```default ASFQWordAttribute(42) ``` * **Bases:** [`ASFBaseAttribute`](#mutagen.asf.ASFBaseAttribute) ## class mutagen.asf.ASFBoolAttribute(value) Bool attribute. ```default ASFBoolAttribute(True) ``` * **Bases:** [`ASFBaseAttribute`](#mutagen.asf.ASFBaseAttribute) ## class mutagen.asf.ASFByteArrayAttribute(value) Byte array attribute. ```default ASFByteArrayAttribute(b'1234') ``` * **Bases:** [`ASFBaseAttribute`](#mutagen.asf.ASFBaseAttribute) ## class mutagen.asf.ASFUnicodeAttribute(value) Unicode string attribute. ```default ASFUnicodeAttribute(u'some text') ``` * **Bases:** [`ASFBaseAttribute`](#mutagen.asf.ASFBaseAttribute) ``` -------------------------------- ### mutagen.File() Source: https://context7.com/quodlibet/mutagen/llms.txt Automatically detects and opens any supported audio file. It returns a FileType subclass instance or None if the format is not recognized. The `easy=True` option provides a simplified interface. ```APIDOC ## `mutagen.File()` — Auto-detect and open any audio file `mutagen.File(filething, options=None, easy=False)` detects the audio format from the first 128 bytes of data, the filename extension, and the presence of existing tags, then returns the appropriate `FileType` subclass instance. Returns `None` if no matching type is found. Set `easy=True` to receive an `EasyMP3`, `EasyMP4`, or `EasyTrueAudio` instance instead of the full-featured variant. ### Description Automatically detects and opens any supported audio file, returning a FileType subclass instance or None if the format is not recognized. The `easy=True` option provides a simplified interface. ### Parameters - **filething**: The file path or file-like object to open. - **options**: Optional. Configuration options for the file type. - **easy**: Optional. Boolean, defaults to False. If True, returns an easy-access instance. ### Request Example ```python import mutagen from mutagen import MutagenError try: audio = mutagen.File("track.mp3") if audio is None: print("Unknown or unsupported format") else: print(audio["artist"]) print(audio.info.length) audio["comment"] = ["Tagged with Mutagen"] audio.save() except MutagenError as e: print(f"Error: {e}") easy_audio = mutagen.File("track.mp3", easy=True) easy_audio["title"] = ["New Title"] easy_audio.save() ``` ### Response #### Success Response - **FileType instance**: An instance of a Mutagen FileType subclass (e.g., `MP3`, `FLAC`) or an easy-access variant if `easy=True`. - **None**: If the audio format is not supported or recognized. #### Response Example ```python # Example of a successful response object (MP3 instance) # Accessing tags and info would be done via the object's methods/attributes ``` ``` -------------------------------- ### Example of AENC frame attributes Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/id3_frames.md Shows the attributes of an AENC (Audio Encryption) frame. Mutagen cannot decrypt files, but it provides access to the frame's metadata like owner, preview start/length, and encryption data. ```python frame = AENC(owner='some_owner', preview_start=100, preview_length=50, data=b'encryption_data') ``` -------------------------------- ### OggSpeex Methods Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/index.md Methods for interacting with Ogg Speex audio files. ```APIDOC ## OggSpeex.info ### Description Retrieves information about the Ogg Speex file. ### Method N/A (Property access) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (200) - **info** (object) - Information about the Ogg Speex file. ### Response Example None ``` ```APIDOC ## OggSpeex.tags ### Description Accesses the tags associated with the Ogg Speex file. ### Method N/A (Property access) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (200) - **tags** (object) - The tags object for the Ogg Speex file. ### Response Example None ``` ```APIDOC ## OggSpeex.score() ### Description Calculates a score for the Ogg Speex file. ### Method N/A (Method call) ### Endpoint N/A ### Parameters None ### Request Example None ### Response None ### Response Example None ``` -------------------------------- ### mutagen.oggvorbis.OggVorbis Source: https://context7.com/quodlibet/mutagen/llms.txt Read and write Ogg Vorbis files with Vorbis comment tags. Supports freeform case-insensitive key-value pairs, multiple values per key, and exposes stream information like length, bitrate, sample rate, and channels. Includes example for embedding cover art using `metadata_block_picture`. ```APIDOC ## `mutagen.oggvorbis.OggVorbis` — Ogg Vorbis Files `OggVorbis(filething)` reads and writes Ogg Vorbis files with Vorbis comment tags (`VCommentDict`). Tags are freeform case-insensitive key=value pairs supporting multiple values per key. `OggVorbisInfo` exposes `length`, `bitrate`, `sample_rate`, and `channels`. ```python from mutagen.oggvorbis import OggVorbis from mutagen import MutagenError audio = OggVorbis("track.ogg") print(f"Length: {audio.info.length:.2f}s") print(f"Bitrate: {audio.info.bitrate} bps") print(f"Rate: {audio.info.sample_rate} Hz") # Read: values are always lists print(audio["artist"]) # [u'Artist Name'] print(audio["title"]) # [u'Song Title'] # Multiple values per key are fully supported audio["artist"] = [u"Primary Artist", u"Featured Artist"] audio["title"] = [u"Song Title"] audio["album"] = [u"Album Name"] audio["tracknumber"] = [u"3"] audio["date"] = [u"2024"] audio["genre"] = [u"Electronic"] audio.save() # Embed cover art via metadata_block_picture (base64-encoded FLAC Picture block) import base64 from mutagen.flac import Picture, error as FLACError pic = Picture() with open("cover.jpg", "rb") as f: pic.data = f.read() pic.type = 3 # COVER_FRONT pic.mime = u"image/jpeg" pic.width = 500 pic.height = 500 pic.depth = 24 encoded = base64.b64encode(pic.write()).decode("ascii") audio["metadata_block_picture"] = [encoded] audio.save() # Read back embedded pictures for b64_data in audio.get("metadata_block_picture", []): try: picture = Picture(base64.b64decode(b64_data)) print(f" Picture: {picture.mime}, {picture.width}x{picture.height}") except FLACError: continue ``` ``` -------------------------------- ### TAK Class Methods Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/index.md Methods available for the TAK audio format handler. ```APIDOC ## TAK.info ### Description Retrieves information about the TAK file. ### Method N/A (Attribute Access) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (N/A) - **info** (TAKInfo) - An object containing detailed information about the TAK file. #### Response Example None ## TAK.score() ### Description Calculates a score for the TAK file. ### Method N/A (Method Call) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (N/A) - **score** (float) - The calculated score. #### Response Example None ``` -------------------------------- ### ID3 Tag Operations Source: https://context7.com/quodlibet/mutagen/llms.txt Demonstrates loading an MP3 file, inspecting its ID3 tags, reading specific frames, setting common text frames, embedding cover art, adding custom frames, managing chapters, and saving the file with different ID3 versions. ```APIDOC ## ID3 Tag Operations ### Description Load an MP3 file, inspect its ID3 tags (version, size), read specific frames like TXXX, set common text frames (TIT2, TPE1, TALB, TDRC, TRCK), embed cover art (APIC), add user-defined text frames (TXXX), manage chapters (CTOC, CHAP), and save the file with ID3v2.4 or ID3v2.3 tags. ### Method ```python from mutagen.id3 import ID3, ID3v1SaveOptions, Encoding, PictureType from mutagen.id3.frames import TIT2, TPE1, TALB, TDRC, TRCK, APIC, TXXX from mutagen.id3.frames.chapter import CTOC, CHAP, CTOCFlags # Load and inspect ID3 tags audio = ID3("track.mp3") print(f"ID3 version: {audio.version}") print(f"Tag size: {audio.size} bytes") # Read frames by type for frame in audio.getall("TXXX"): print(f" TXXX:{frame.desc} = {frame.text}") # Set common text frames audio.add(TIT2(encoding=Encoding.UTF8, text=[u"Song Title"])) audio.add(TPE1(encoding=Encoding.UTF8, text=[u"Artist Name"])) audio.add(TALB(encoding=Encoding.UTF8, text=[u"Album Name"])) audio.add(TDRC(encoding=Encoding.UTF8, text=[u"2024"])) audio.add(TRCK(encoding=Encoding.UTF8, text=[u"1/12"])) # Embed cover art with open("cover.jpg", "rb") as f: cover_data = f.read() audio.add( APIC( encoding=Encoding.UTF8, mime=u"image/jpeg", type=PictureType.COVER_FRONT, desc=u"Cover", data=cover_data, ) ) # Add a user-defined text frame audio.add(TXXX(encoding=Encoding.UTF8, desc=u"MusicBrainz Track Id", text=[u"abcd-1234"])) # Add chapters audio.add( CTOC( element_id=u"toc", flags=CTOCFlags.TOP_LEVEL | CTOCFlags.ORDERED, child_element_ids=[u"chp1", u"chp2"], sub_frames=[TIT2(text=[u"Table of Contents"])] ) ) audio.add(CHAP(element_id=u"chp1", start_time=0, end_time=30000, sub_frames=[TIT2(text=[u"Chapter 1"])])) # Save as ID3v2.4 (default) with ID3v1 fallback tag audio.save(v1=ID3v1SaveOptions.CREATE) # Save as ID3v2.3 (for wider compatibility) audio_v3 = ID3("track.mp3", v2_version=3) audio_v3.update_to_v23() audio_v3.save(v2_version=3, v23_sep="/") # Delete all ID3 tags # audio.delete(delete_v1=True, delete_v2=True) ``` ``` -------------------------------- ### WAVE Class Methods Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/index.md Methods available for the WAVE audio format handler. ```APIDOC ## WAVE.tags ### Description Retrieves the tags associated with the WAVE file. ### Method N/A (Attribute Access) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (N/A) - **tags** (dict) - A dictionary representing the tags. #### Response Example None ## WAVE.info ### Description Retrieves information about the WAVE file. ### Method N/A (Attribute Access) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (N/A) - **info** (WaveStreamInfo) - An object containing detailed information about the WAVE file. #### Response Example None ## WAVE.score() ### Description Calculates a score for the WAVE file. ### Method N/A (Method Call) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (N/A) - **score** (float) - The calculated score. #### Response Example None ## WAVE.add_tags() ### Description Adds or updates tags in the WAVE file. ### Method N/A (Method Call) ### Endpoint N/A ### Parameters - **tags** (dict) - A dictionary of tags to add or update. ### Request Example None ### Response #### Success Response (N/A) None #### Response Example None ## WAVE.load() ### Description Loads a WAVE file. ### Method N/A (Method Call) ### Endpoint N/A ### Parameters - **filename** (str) - The path to the WAVE file. ### Request Example None ### Response #### Success Response (N/A) - **WAVE** (WAVE) - The loaded WAVE object. #### Response Example None ``` -------------------------------- ### Load FLAC by filename Source: https://context7.com/quodlibet/mutagen/llms.txt Load a FLAC file by explicitly providing the filename. Access file information like sample rate through the `.info` attribute. ```python flac2 = FLAC(filename="track.flac") print(flac2.info.sample_rate) ``` -------------------------------- ### Access StreamInfo from FileType Source: https://github.com/quodlibet/mutagen/blob/main/docs/user/classes.md Illustrates how to access the StreamInfo object from a FileType instance, which contains details about the audio stream. The pprint() method provides a human-readable summary. ```python >>> type(f.info) >>> print(f.info.pprint()) Ogg Vorbis, 346.43 seconds, 499821 bps >>> ``` -------------------------------- ### OggOpus Methods Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/index.md Methods for interacting with Ogg Opus audio files. ```APIDOC ## OggOpus.info ### Description Retrieves information about the Ogg Opus file. ### Method N/A (Property access) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (200) - **info** (object) - Information about the Ogg Opus file. ### Response Example None ``` ```APIDOC ## OggOpus.tags ### Description Accesses the tags associated with the Ogg Opus file. ### Method N/A (Property access) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (200) - **tags** (object) - The tags object for the Ogg Opus file. ### Response Example None ``` ```APIDOC ## OggOpus.score() ### Description Calculates a score for the Ogg Opus file. ### Method N/A (Method call) ### Endpoint N/A ### Parameters None ### Request Example None ### Response None ### Response Example None ``` -------------------------------- ### MPEGInfo.pprint() Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/index.md Prints a human-readable representation of MPEGInfo metadata. ```APIDOC ## MPEGInfo.pprint() ### Description Prints a human-readable representation of MPEGInfo metadata. ### Method `pprint()` ### Parameters None ### Response None (prints to console) ``` -------------------------------- ### Read/Write APEv2 Tags Directly Source: https://context7.com/quodlibet/mutagen/llms.txt Shows how to read and write APEv2 tags directly using the APEv2 class. Handles APENoHeaderError for new files and demonstrates setting various tag fields. Remember to save the changes. ```python from mutagen.apev2 import APEv2, APEv2File, APENoHeaderError from mutagen import MutagenError # Read/write APEv2 tag directly on any file try: tag = APEv2("track.ape") except APENoHeaderError: tag = APEv2() # Create a new tag tag["Title"] = u"Song Title" tag["Artist"] = u"Artist Name" tag["Album"] = u"Album Name" tag["Year"] = u"2024" tag["Track"] = u"5/12" tag["Genre"] = u"Electronic" tag.save("track.ape") # Print all tags print(tag.pprint()) # Title=Song Title # Artist=Artist Name # Use APEv2File as a FileType for automatic file handling audio = APEv2File("track.ape") print(audio.tags["Artist"]) # APEv2 value object audio.delete() # Remove APEv2 tag from file ``` -------------------------------- ### OggTheoraInfo Method: pprint Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/oggtheora.md Prints stream information for the Ogg Theora file. ```APIDOC ## method mutagen.oggtheora.OggTheoraInfo.pprint * **Returns:** Print stream information * **Return type:** [text](base.md#mutagen.text) ``` -------------------------------- ### WavPack Class Methods Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/index.md Methods available for the WavPack audio format handler. ```APIDOC ## WavPack.info ### Description Retrieves information about the WavPack file. ### Method N/A (Attribute Access) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (N/A) - **info** (WavPackInfo) - An object containing detailed information about the WavPack file. #### Response Example None ## WavPack.score() ### Description Calculates a score for the WavPack file. ### Method N/A (Method Call) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (N/A) - **score** (float) - The calculated score. #### Response Example None ``` -------------------------------- ### WavPackInfo Class Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/index.md Provides information about WavPack audio files. ```APIDOC ## Class: WavPackInfo ### Description Provides access to metadata and properties of a WavPack audio file. ### Attributes - **channels** (int): The number of audio channels. - **length** (float): The duration of the audio in seconds. - **sample_rate** (int): The sample rate of the audio in Hz. - **bits_per_sample** (int): The number of bits per sample. - **version** (tuple): The WavPack version information. ### Methods - **pprint()**: Prints a human-readable representation of the WavPackInfo object. ``` -------------------------------- ### Load and Inspect ID3 Tags Source: https://context7.com/quodlibet/mutagen/llms.txt Load an MP3 file, print its ID3 version and tag size, and iterate through custom text frames (TXXX). ```python from mutagen.id3 import ID3, ID3v1SaveOptions from mutagen.id3.frames import TIT2, TPE1, TALB, TDRC, TRCK, TXXX, APIC, CTOC, CHAP from mutagen.id3.enums import Encoding, PictureType audio = ID3("track.mp3") print(f"ID3 version: {audio.version}") # (2, 4, 0) print(f"Tag size: {audio.size} bytes") for frame in audio.getall("TXXX"): print(f" TXXX:{frame.desc} = {frame.text}") audio.add(TIT2(encoding=Encoding.UTF8, text=[u"Song Title"])) audio.add(TPE1(encoding=Encoding.UTF8, text=[u"Artist Name"])) audio.add(TALB(encoding=Encoding.UTF8, text=[u"Album Name"])) audio.add(TDRC(encoding=Encoding.UTF8, text=[u"2024"])) audio.add(TRCK(encoding=Encoding.UTF8, text=[u"1/12"])) with open("cover.jpg", "rb") as f: cover_data = f.read() audio.add( APIC( encoding=Encoding.UTF8, mime=u"image/jpeg", type=PictureType.COVER_FRONT, desc=u"Cover", data=cover_data, ) ) audio.add(TXXX(encoding=Encoding.UTF8, desc=u"MusicBrainz Track Id", text=[u"abcd-1234"])) audio.add( CTOC( element_id=u"toc", flags=CTOCFlags.TOP_LEVEL | CTOCFlags.ORDERED, child_element_ids=[u"chp1", u"chp2"], sub_frames=[TIT2(text=[u"Table of Contents"])] ) ) audio.add(CHAP(element_id=u"chp1", start_time=0, end_time=30000, sub_frames=[TIT2(text=[u"Chapter 1"])])) audio.save(v1=ID3v1SaveOptions.CREATE) audio_v3 = ID3("track.mp3", v2_version=3) audio_v3.update_to_v23() audio_v3.save(v2_version=3, v23_sep="/") # audio.delete(delete_v1=True, delete_v2=True) ``` -------------------------------- ### Instantiate ID3 Tag Object Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/id3.md Create an ID3 tag object for a given file or an empty one. If a file is provided, it will be loaded immediately. ```python ID3("foo.mp3") # same as t = ID3() t.load("foo.mp3") ``` -------------------------------- ### Load FLAC using explicit keyword argument Source: https://context7.com/quodlibet/mutagen/llms.txt Load a FLAC file using the `fileobj` keyword argument, which bypasses type guessing. Access tags using dictionary-like syntax. ```python with open("track.flac", "rb") as fobj: flac = FLAC(fileobj=fobj) print(flac["title"]) ``` -------------------------------- ### EasyMP3.info Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/index.md Provides access to MPEG audio information for an EasyMP3 file. ```APIDOC ## EasyMP3.info ### Description Provides access to MPEG audio information for an EasyMP3 file. ### Method Attribute access: `EasyMP3.info` ### Parameters None ### Response An `MPEGInfo` object containing audio details. ``` -------------------------------- ### OggFLAC Methods Source: https://github.com/quodlibet/mutagen/blob/main/docs/api/index.md Methods for interacting with Ogg FLAC audio files. ```APIDOC ## OggFLAC.info ### Description Retrieves information about the Ogg FLAC file. ### Method N/A (Property access) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (200) - **info** (object) - Information about the Ogg FLAC file. ### Response Example None ``` ```APIDOC ## OggFLAC.tags ### Description Accesses the tags associated with the Ogg FLAC file. ### Method N/A (Property access) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (200) - **tags** (object) - The tags object for the Ogg FLAC file. ### Response Example None ``` -------------------------------- ### Load FLAC File, Set Title, and Save Source: https://github.com/quodlibet/mutagen/blob/main/docs/user/gettingstarted.md Load a FLAC file, set its title tag, print all tag data, and save the changes. This is useful for modifying FLAC metadata. ```python from mutagen.flac import FLAC audio = FLAC("example.flac") audio["title"] = u"An example" audio.pprint() audio.save() ```