Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate BitRate for a VBR mp3 without downloading the entire file?

I want to get the information of the duration for a remote mp3 file at the beginning of its downloading. I can get the frames at first but doesn't know which must be read, Xing or VBRi.

How can I get this information by reading the tags?

MemoryStream ms = new MemoryStream();
waveOut.Play();
long offset = from;
ms.Position = 0;
byte[] decBuffer = new byte[50 * 1024];
while (true)
{
   if (paused)
   {
      waveOut.Stop();
      bwProvider.ClearBuffer();
      break;
   }
      lock (LockObj)
      {
         byte[] readed = Helper.ReadStreamPartially(localStream, offset, 100 * 1024, orders);
         if (readed == null)
            continue;
         ms = new MemoryStream(readed);
      }
      Mp3Frame frame;
      try
      {
         frame = Mp3Frame.LoadFromStream(ms);
      }
      catch
      {
         continue;
      }
      if (frame == null)
         continue;

      int decompressed = decompressor.DecompressFrame(frame, decBuffer, 0);

      bwProvider.AddSamples(decBuffer, 0, decompressed);

      if (Helper.IsBufferNearlyFull(bwProvider))
          Thread.Sleep(500);

      offset += ms.Position;

 }
like image 632
Ali Tor Avatar asked Oct 30 '22 13:10

Ali Tor


1 Answers

A bit late but if anyone else needs it...

This CodeProject article has a lot of good formation about MP3 header.

  • Find the XING header's start position.
  • The 8th byte onwards is an integer of total frames (if exists will be 4 bytes, Big endian).

Each MPEG frame gives a constant amount of samples per frame, determined by sampling rate, regardless of total bytes-in-frameX. You can estimate with a calculation like :

durationVBR = single_frame_time * total_frames; 

Where...

single_frame_time = (SampleRate / SamplesPerFrame) * 1000;

The constants for SamplesPerFrame are :

MPEG-1

  • Layer I = 384 samples.
  • Layer II = 1152 samples.
  • Layer III = 1152 samples.

MPEG-2

  • Layer I = 384 samples.
  • Layer II = 1152 samples.
  • Layer III = 576 samples.
like image 157
VC.One Avatar answered Nov 15 '22 05:11

VC.One