'How to get the duration of an mp3 file

I tried many methods but did not get the exact length value of an mp3 file.

With moviepy:

audiofile = AudioFileClip(url)
print("duration moviepy: " + str(audiofile.duration))

I get result:

duration moviepy: 183.59

With mutagen:

from mutagen.mp3 import MP3
audio = MP3(url)
print("duration mutagen: " + str(audio.info.length))

I received another value of duration:

duration mutagen: 140.93416666666667

Actual duration value when I open the file using windows media player: 2m49s

I don't know what happens to my audio file, I test a few files from the music website and still get the correct value. This is my audio file



Solution 1:[1]

try pyxsox

I tried to use pysox to the audio file which includes this question post

note: pysox needs SOX cli.

how to use it is like this.

import sox
mp3_path = "YOUR STRANGE MP3 FILEPATH"
length = sox.file_info.duration(mp3_path)
print("duration sec: " + str(length))
print("duration min: " + str(int(length/60)) + ':' + str(int(length%60)))

results are

duration sec: 205.347982
duration min: 3:25

and the others information on that mp3 file's duration.

ID3 information => 2.49
mutagen => 2:20
pysox => 3:25
actural length => 3:26

mutagen seems just to read ID3 information.

Solution 2:[2]

Using Mutagen

pip install mutagen

python:

import os
from mutagen.mp3 import MP3

def convert_seconds(seconds):
    hours = seconds // 3600
    seconds %= 3600
    minutes = seconds // 60
    seconds %= 60
    return "%02d:%02d:%02d" % (hours, minutes, seconds)

path = "Your mp3 files floder."
total_length = 0
for root, dirs, files in os.walk(os.path.abspath(path)):
    for file in files:
        if file.endswith(".mp3"):
            audio = MP3(os.path.join(root, file))
            length = audio.info.length
            total_length += length

hours, minutes, seconds = convert_seconds(total_length).split(":")
print("total duration: " + str(int(hours)) + ':' + str(int(minutes)) + ':' + str(int(seconds)))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 saneryee