Skip to main content

Mutagen - How To Examples in Python

Mutagen: How To Examples in Python

Mutagen is a Python library that allows you to read, write, and manipulate audio metadata. It supports a wide range of audio formats, including MP3, FLAC, Ogg Vorbis, and more. In this tutorial, we will cover several examples of how to use Mutagen in Python.

Example 1: Reading Metadata

To start, let's see how to read the metadata from an audio file. First, make sure you have installed Mutagen by running pip install mutagen.

from mutagen import File

# Open the audio file
audio = File("example.mp3", easy=True)

# Extract metadata
title = audio["title"][0]
artist = audio["artist"][0]
album = audio["album"][0]
duration = audio.info.length

# Print the metadata
print("Title:", title)
print("Artist:", artist)
print("Album:", album)
print("Duration:", duration, "seconds")

Expected Output:

Title: My Song
Artist: John Doe
Album: My Album
Duration: 180.0 seconds

In this example, we open an MP3 file called "example.mp3" using the File class from Mutagen. We then extract the metadata fields like title, artist, album, and duration using their respective keys. Finally, we print out the extracted metadata.

Example 2: Writing Metadata

Mutagen also allows us to modify and write metadata to an audio file. Let's see how to change the title of an MP3 file.

from mutagen import File
from mutagen.id3 import ID3, TIT2, TPE1

# Open the audio file
audio = File("example.mp3", easy=True)

# Modify the title
audio["title"] = TIT2(encoding=3, text="New Title")

# Save the changes
audio.save()

Expected Output:

The title of the "example.mp3" file will be changed to "New Title".

In this example, we open an MP3 file using the File class from Mutagen. We then modify the title field by assigning a new value to audio["title"]. Finally, we save the changes using the save() method.

Example 3: Extracting Album Art

Mutagen can also extract album art from audio files. Let's see how to save the album art as an image file.

from mutagen import File

# Open the audio file
audio = File("example.mp3", easy=True)

# Extract album art
if "covr" in audio:
cover = audio["covr"][0]
with open("cover.jpg", "wb") as file:
file.write(cover)

Expected Output:

The album art will be saved as a file named "cover.jpg".

In this example, we open an audio file and check if there is album art available. If the "covr" key exists, we extract the first cover art and save it as a JPEG image file named "cover.jpg".

Example 4: Adding Album Art

In addition to extracting album art, Mutagen allows us to add new album art to audio files. Let's see how to add a cover image to an MP3 file.

from mutagen import File
from mutagen.id3 import ID3, APIC

# Open the audio file
audio = File("example.mp3", easy=True)

# Create a new APIC tag with the cover image
audio["APIC"] = APIC(
encoding=3,
mime="image/jpeg",
type=3,
desc=u"Cover",
data=open("cover.jpg", "rb").read()
)

# Save the changes
audio.save()

Expected Output:

The "example.mp3" file will have a new album art added using the "cover.jpg" image file.

In this example, we open an MP3 file and create a new APIC tag with the cover image. We provide the necessary parameters such as encoding, mime type, description, and the image data. Finally, we save the changes using the save() method.

Example 5: Removing Metadata

Mutagen allows us to remove specific metadata fields from audio files. Let's see how to remove the album field from an MP3 file.

from mutagen import File

# Open the audio file
audio = File("example.mp3", easy=True)

# Remove the album field
del audio["album"]

# Save the changes
audio.save()

Expected Output:

The album field will be removed from the "example.mp3" file.

In this example, we open an MP3 file and delete the "album" field using the del keyword. Finally, we save the changes using the save() method.

Example 6: Converting Audio Formats

Mutagen can also be used to convert audio files from one format to another. Let's see how to convert an MP3 file to FLAC format.

from mutagen import File

# Open the MP3 file
audio = File("example.mp3", easy=True)

# Convert to FLAC format
audio.save("example.flac", format="flac")

Expected Output:

The "example.mp3" file will be converted to the FLAC format and saved as "example.flac".

In this example, we open an MP3 file using Mutagen and save it in FLAC format by specifying the desired format as "flac" in the save() method.

Example 7: Reading Audio Tags

Mutagen allows us to read audio tags such as bitrate, sample rate, and channel count. Let's see how to retrieve this information from an audio file.

from mutagen import File

# Open the audio file
audio = File("example.mp3", easy=True)

# Extract audio tags
bitrate = audio.info.bitrate
sample_rate = audio.info.sample_rate
channels = audio.info.channels

# Print the audio tags
print("Bitrate:", bitrate, "kbps")
print("Sample Rate:", sample_rate, "Hz")
print("Channels:", channels)

Expected Output:

Bitrate: 320 kbps
Sample Rate: 44100 Hz
Channels: 2

In this example, we open an audio file and extract the bitrate, sample rate, and channel count using the info attribute of the File object. We then print out the retrieved information.

Example 8: Calculating Audio Duration

Mutagen allows us to calculate the duration of an audio file. Let's see how to retrieve the duration of an MP3 file.

from mutagen import File

# Open the audio file
audio = File("example.mp3", easy=True)

# Calculate the duration
duration = audio.info.length

# Print the duration
print("Duration:", duration, "seconds")

Expected Output:

Duration: 180.0 seconds

In this example, we open an audio file and calculate its duration using the length attribute of the info object. Finally, we print out the calculated duration.

Example 9: Extracting Lyrics

Mutagen can also extract lyrics from audio files. Let's see how to retrieve and print the lyrics of a song.

from mutagen import File
from mutagen.id3 import ID3, USLT

# Open the audio file
audio = File("example.mp3", easy=True)

# Extract lyrics
if "USLT" in audio:
lyrics = audio["USLT"][0].text

# Print the lyrics
print("Lyrics:")
print(lyrics)
else:
print("No lyrics found.")

Expected Output:

The lyrics of the song will be printed if available, otherwise "No lyrics found." will be printed.

In this example, we open an audio file and check if there are lyrics available by looking for the "USLT" key. If lyrics are found, we extract and print them. Otherwise, we print a message indicating that no lyrics were found.

Example 10: Batch Processing

Mutagen can be used to perform batch processing on multiple audio files. Let's see how to read the metadata from all the MP3 files in a directory.

import os
from mutagen import File

# Specify the directory path
directory = "audio_files"

# Iterate over the files in the directory
for filename in os.listdir(directory):
if filename.endswith(".mp3"):
filepath = os.path.join(directory, filename)

# Open the audio file
audio = File(filepath, easy=True)

# Extract metadata
title = audio["title"][0]
artist = audio["artist"][0]
album = audio["album"][0]
duration = audio.info.length

# Print the metadata
print("File:", filename)
print("Title:", title)
print("Artist:", artist)
print("Album:", album)
print("Duration:", duration, "seconds")

Expected Output:

The metadata of each MP3 file in the "audio_files" directory will be printed.

In this example, we specify the directory path containing the audio files. We then iterate over all the files in the directory and check if they have the ".mp3" extension. For each MP3 file found, we open it using Mutagen and extract the metadata fields. Finally, we print out the metadata for each file.

These examples cover some of the common use cases of Mutagen in Python. With Mutagen, you can easily manipulate audio metadata, extract information, and perform various operations on audio files.