Feed Sign in with OpenID OpenID

Simon Willison’s Weblog

Extracting the length from MP3 files with Python

Ned Batchelder recently wrote about the difficulties involved in extracting the length from an MP3 file. We’re going to need to solve this problem soon at work; luckily, it seems that the answer may lie in the Python bindings for mpgedit, an audio file editing library available for both Windows and Linux.

After installing the Windows package and experimenting for a while, I managed to extract the time from one of my test files using the following:

>>> import mpgedit
>>> play = mpgedit.Play('example.mp3')
>>> play.total_time()
(213, 129)
>>> secs, msecs = play.total_time()
>>> mins = secs / 60
>>> secs = secs - mins * 60
>>> print "%d:%02d minutes" % (mins, secs)
3:33 minutes

However, for other files total_time() is returning (-1, -1). I’m sure there’s a solution to this but I haven’t stumbled across it yet.

This is Extracting the length from MP3 files with Python by Simon Willison, posted on 4th December 2003.

View blog reactions

Next: Dates on the web

Previous: Downloading your hotmail inbox

5 comments

  1. It's not difficult reading MP3-files in Python, see mp3.py for some code I use in an MP3-streaming thingy. Something along the lines of secs = sum([ mp3.time(h) for h,f in mp3.frames(open('...'))]) should give you the length of your MP3-file.

    Sune Kirkeby - 4th December 2003 08:39 - #

  2. This also needs a C extension but my wrapper around bitzi's bitcollider should also do this.

    Download the wrapper

    icepick - 4th December 2003 16:58 - #

  3. Would mp3info be of any help?

    pete - 4th December 2003 17:46 - #

  4. I've written a playlist generator script weeks ago and also used pymad to extract the length. It's very simple:

    import mad
    
    mf = mad.MadFile("foo.mp3")
    track_length_in_milliseconds = mf.total_time()
    

    pymad is here and my script is here

    Lawrence Oluyede - 4th December 2003 20:57 - #

  5. Thanks to Sune's mp3.py above, I've completed my playlist generator: m3u files in a tree, take 2

    Ned Batchelder - 5th January 2004 00:56 - #

Comments are closed.

Previously hosted at http://simon.incutio.com/archive/2003/12/04/mp3lengths

A django site