#255: How to Work With MP3 Metadata
The metadata in audio files help us to organise songs and allows tools like iTunes to show us the artist of the song it is playing. As long as the metadata is correct, everything works nicely. But what can we do if the data is wrong or not set at all? Let us explore our options and set some metadata.
Find a library
There are a few libraries out there that allow us to use Python to access the metadata in audio files. As so often, not all libraries offer what they promise and not every library can write metadata. Make sure that your library matches your use case.
I used Mutagen in the past and hope they will soon release a new update. We can install it with this command:
Read metadata from a MP3 file
In an MP3 file we have two main parts of metadata: a technical part about the file itself and a part for the content (artist, album, etc.). With Mutagen we must read those two parts through different objects. The MP3 object gives us the technical parts, while the content metadata is in EasyID3:
If we run this code against a sample.mp3 file, we should see something like this:
python read_metadata_mp3.py
file: sample.mp3
--------------------------------------------------
length: 3.239183673469388
sample_rate: 44100
bitrate: 127998
bitrate_mode: BitrateMode.CBR
channels: 2
pprint: MPEG 1 layer 3, 127998 bps (CBR), 44100 Hz, 2 chn, 3.24 seconds
--------------------------------------------------
**************************************************
The file currently only has technical details but no content metadata. Let us change that.
Write metadata to a MP3 file
We can only modify the content metadata and to do that we use the EasyID3 class again. This gives us a helpful abstraction over the ID3 standard and allows us to use “artist” instead of TPE1. To figure out what keys we can use, we need to look at the code of EasyID3:
We can take the keys from above and use it like a dictionary. Do not forget to save the file when you are done, otherwise your metadata will be gone.
If we run this code, we should get an output like this one:
python write_metadata_mp3.py
file: sample.mp3
--------------------------------------------------
--------------------------------------------------
write metadata
--------------------------------------------------
album=Python rules
albumartist=Jon Doe II
artist=Jon Doe
date=2024
genre=Education
title=Writing Metadata
tracknumber=1
We can see the metadata in the Windows Explorer as part of the file properties:

Next
With Mutagen we can not only read, but also write metadata for MP3 files. Should you want to fix your metadata in the old MP3 collection, then this library is a great help.
Next week we explore the little differences that come with Flac audio files.