DEV Community

@kon_yu
@kon_yu

Posted on

6 1

How to Get mp3 file's Durations with Python

How to get durations of mp3 files are two ways.
One of them is using mutagen, the other is using pysox.
Each method has its own advantages and disadvantages.

The way using mutagen is lightweight, and faster than the way using pysox.

That's why mutagen just checks ID3 tag of mp3 files. The other hand, pysox seems to check binaries of mp3 files through Sox CLI.

The pysox method allows us to determine the duration without using ID3 information, i.e. to recognize files with invalid ID3 information or files without ID3 information. Using pysox, you can find out the duration of a file without using ID3 information, i.e. you can detect the duration of a file with invalid or no ID3 information.

The mutagen way example



from mutagen.mp3 import MP3

def mutagen_length(path):
    try:
        audio = MP3(path)
        length = audio.info.length
        return length
    except:
        return None

length = mutagen_length(wav_path)
print("duration sec: " + str(length))
print("duration min: " + str(int(length/60)) + ':' + str(int(length%60)))


Enter fullscreen mode Exit fullscreen mode

The pysox way example

note: pysox needs SOX cli.



import sox

def sox_length(path):
    try:
        length = sox.file_info.duration(path)
        return length
    except:
        return None

length = sox_length(mp3_path)

print("duration sec: " + str(length))
print("duration min: " + str(int(length/60)) + ':' + str(int(length%60)))


Enter fullscreen mode Exit fullscreen mode

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)) +
…

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay