12

I try to calculate mp3 duration by using bitrate and file size , after some search i found this formula:

(mp3sizeInByte*0.008)/bitrate

i am using mp3sizeInByte*0.008 to convert byte to Kbits.

but its not so accurate , in result there is couple second different compare to actual mp3 duration.

i want know this right formula ?

alireza
  • 537
  • 1
  • 5
  • 18
  • I don't see a question mark anywhere in your post but anyways how are you getting your value for the bitrate? How is the file encoded? – helrich Apr 07 '15 at 15:07
  • @helrich i am using ffmpeg for extract mp3 metadata . – alireza Apr 07 '15 at 15:34
  • 2
    Even with CBR the _effective_ bit rate can vary. [See here](http://wiki.hydrogenaud.io/index.php?title=Bit_reservoir) for some additional info. Overall if a several minute mp3 is off by a few seconds, that's still pretty good. I would really look into parsing the ID3 tags to get the info you're after. – helrich Apr 07 '15 at 16:14

2 Answers2

23

You can calculate the size using the following formula:

x = length of song in seconds

y = bitrate in kilobits per second

(x * y) / 8

We divide by 8 to get the result in kilobytes(kb).

So for example if you have a 3 minute song

3 minutes = 180 seconds

128kbps * 180 seconds = 23,040 kilobits of data 23,040 kilobits / 8 = 2880 kb

You would then convert to Megabytes by dividing by 1024:

2880/1024 = 2.8125 Mb

If all of this was done at a different encoding rate, say 192kbps it would look like this:

(192 * 180) / 8 = 4320 kb / 1024 = 4.21875 Mb

btwiuse
  • 2,585
  • 1
  • 23
  • 31
Yogesh Nikam
  • 633
  • 5
  • 20
  • Isn't the question asking how to get the length of song in first place? Why in the world is this an accepted answer. – cyberwombat Dec 18 '21 at 17:47
  • @cyberwombat Because you just have to readjust the equation to be: `timeInSec = (sizeInKb * 8)/kbPerSec`. Quite trivial, only took me 20 minutes to do (insert crying emoji) – Oliver Wagner Sep 06 '22 at 14:33
3

If anyone else comes across trying to calculate bitrate in JavaScript with Web Audio API this is how I accomplished it:

<input type="file" id="myFiles" onchange="parseAudioFile()"/>
function parseAudioFile(){
  const input = document.getElementById('myFiles');
  const files = input.files;
  const file = files && files.length ? files[0] : null;
  if(file && file.type.includes('audio')){
    const audioContext = new (window.AudioContext || window.webkitAudioContext)();
    const reader = new FileReader();
    reader.onload = function(e){
      const arrayBuffer = e.target.result;
      audioContext.decodeAudioData(arrayBuffer)
        .then(function(buffer){
          const duration = buffer.duration || 1;
          const bitrate = Math.floor((file.size * 0.008) / duration);
          // Do something with the bitrate
          console.log(bitrate);
        });
    };
    reader.readAsArrayBuffer(file);
  }
}
Logus Graphics
  • 1,793
  • 16
  • 17