Norsolia

Blog / Reading an MP3's length from its frames

Reading an MP3's length from its frames

When you upload an episode, the feed needs its length for itunes:duration. We work it out without a media library, from the file itself.

An MP3 is a stream of frames

An MP3 is a run of small frames, each starting with a four-byte header. The header encodes the MPEG version, the layer, the bitrate and the sample rate. From those you know two things: how many audio samples the frame holds (1152 for MPEG-1 Layer III) and how many bytes it occupies.

Two ways to the total

For a variable-bitrate file, the first frame usually carries a Xing or Info header with the total frame count; multiply by samples-per-frame and divide by the sample rate. For a constant-bitrate file with no such header, we walk the frames, count them, and do the same arithmetic. Either way the duration comes from the audio, not from a value someone typed.

Why M4A is different

An M4A (MP4 container) stores duration in a moov atom whose position is not fixed and can sit at the end of the file. Parsing it reliably is more than a header read, so for M4A we ask you for the length on upload and record it. It is the honest trade: read it where we can, ask where we cannot.

All of this is plain Python with no dependencies, which keeps the host small enough for two people to run.

All posts