Go Down

Topic: Determine duration of mp3 file (Read 106 times) previous topic - next topic


Can anyone explain how to determine the duration of a mp3 file on a Nano? Code snippet would be great!

I dont have much space to include a full MP3 handling library. I am using Adafruit VS1053 to play the mp3s.


Jun 30, 2020, 07:13 pm Last Edit: Jun 30, 2020, 08:18 pm by DVDdoug
I don't know exactly, but the foolproof method is to go through the file frame-by-frame and sum-up the duration (or number of samples) in each frame. 

I found some (non-Arduino) code for reading/analyzing MP3 frames here.      Also see Inside The MP3 Codec and MP3 Theory.

If you have a constant bitrate MP3 (CBR) with no embedded artwork you can can get the approximate playing time from the bitrate and file size.    Bitrate (kpbs) is kilobits per second so you can multiply by 8 to get kilobytes per second.

There may be some additional information in a VBR header (or LAME or XING header) that can used to quickly calculate playing time but it's frequently missing or incorrect.

There's probably no way to do this with an Arduino since you're probably using an audio shield and the Arduino can't directly access the MP3 file.

You might have to store the (known) duration separately in flash or EEPROM.


I believe Adafruit's VS1053 board has the microcontroller read the MP3 from the SD card and then send that data to the VS1053 chip.

MP3 files have a 32 bit header on each frame of audio data.


The size of the frame can be calculated from info in those 32 bits.  VBR files use this format, but each header can have a different bitrate, so each frame size can be different so you have to redo the frame size calculation for every frame.  Some frames also have an optional padding byte, so don't forget to add that to the size for the frames with that bit set.  Once you know the size, you can just skip forward that far in the file and you (should always) find the next frame header.  If it doesn't have the 12 all-ones (a corrupted file), then you could read until you find a pattern of 12 all-one bits and try parsing that as the next header.

Normally MP3 has 1152 audio samples per frame.  You can probably just divide 1152 by the sample rate from the header to get the time duration of the frame.  The sample rate usually never changes within a file, so you could just it from the first frame, then scan through the file to count up how many 1152 sample frames it has.

Go Up