Duration of an MP3/wav audio file

audio, delphi, mp3

Solution

You can calculate the duration by dividing the size of the file by the bit rate. You can get the bit rate from one of the frame headers. Of course, this won't work for variable rate MP3s, where you can have a different rate for each frame.

Using the Header Layout (it's just four bytes):

Open the MP3 in a stream

Find the beginning of the first frame header by reading until you find the sync header, which has 11 consecutive bits set to 1. This used to be 12, but it was tweaked to allow for MPEG version 2.5.

Determine the MPEG version ID. For the purposes of finding the bit rate, V2.5 is the same as V2

Determine the layer description

Read the bit rate index

Using the MPEG version, layer description and bit rate index, determine the actual bit rate from the bit rate index table in the linked header reference

Divide the file size in kilobits ((8 * size in bytes) / 1000) by the bit rate to get the duration in seconds

I couldn't find a Delphi sample, but here is a C# implementation that uses this technique for reference purposes. See the getLengthInSeconds method.

Problem

How do you get the duration (in minutes and seconds) of an MP3/wav audio file in Delphi ?

Original source