How to find the duration of an MP3 file in Python

In this tutorial, we will learn how to find the duration of an mp3 file using python. You may require this as a part of a feature in your project or for experimental purposes.

Python Program to find the duration of mp3 file

For this purpose, we need not complicate the process by handling the mp3 file in its binary form instead, we will make use of an external library called mutagen.

Before proceeding further, we first need to install mutagen. This can easily be done with the help of the inbuilt Python package manager, pip.

Open up the command prompt and type in the following command.

pip3 install mutagen

This will install the package and since it doesn’t have any additional dependencies, that is all you need to proceed.

To test if the package was installed correctly, type the following line of code on your python shell.

import mutagen

We will now discuss the code required to find the duration of the mp3 file.

First, we need to import mutagen or specifically the mp3 class of the library. We can do it as follows.

from mutagen.mp3 import MP3

Next, we need to create an object of type MP3 by referencing the location of our mp3 file. This can be done by passing the directory address of the mp3 file as a string.

audio = MP3("D:\path\to\the\file")

We will now access the info member of the MP3 class which will contain all the metadata of the referenced mp3 file. We can then access the length member of the info object which will give us the length of the mp3 file in terms of seconds which we can convert into more readable formats.

audio_info = audio.info    
length_in_secs = int(audio_info.length)

That’s the entire process of finding the duration of the mp3 file. The complete code for it is attached below.

from mutagen.mp3 import MP3

# function to convert the seconds into readable format
def convert(seconds):
    hours = seconds // 3600
    seconds %= 3600

    mins = seconds // 60
    seconds %= 60

    return hours, mins, seconds

# Create an MP3 object
# Specify the directory address to the mp3 file as a parameter
audio = MP3("G:\Python37\Sample.mp3")

# Contains all the metadata about the mp3 file
audio_info = audio.info    

length_in_secs = int(audio_info.length)

hours, mins, seconds = convert(length_in_secs)

print("Hours:", hours)
print("Minutes:", mins)
print("Seconds:", seconds)

The output for the above code will look like

Hours: 0
Minutes: 2
Seconds: 37

You can read the documentation of the above library here, in case you need to handle mp3 files for any other purpose.

Leave a Reply

Your email address will not be published. Required fields are marked *