Calculate MP3 duration based on bitrate and file size

I am trying to calculate mp3 duration using bitrate and file size, after some searching I found this formula:

(mp3sizeInByte*0.008)/bitrate

I use mp3sizeInByte*0.008to convert bytes to kilobytes.

but its not so accurate, as a result there is a couple of second different comparisons with the actual duration of mp3.

I want to know this correct formula?

+6
source share
2 answers

You can calculate the size using the following formula:

x = song length in seconds

y = bitrate in kilobits per second

(x * y) / 8

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

So for example, if you have a 3 minute song

3 minutes = 180 seconds

128 / * 180 = 23 040 23 040 /8 = 2880

, 1024:

2880/1024 = 2,8125

, , 192 /, :

(192 * 180)/8 = 4320 /1024 = 4,21875

+11

- JavaScript API Web Audio, :

<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);
  }
}
0

All Articles