How, using the tag <audio> , display the bitrate using js?

  • 2
    Maybe they get data from the server by bitrate, along with the audio stream. - Vladimir Gamalyan
  • If you have seen the implementation on "some sites", try to parse their implementation. - Sergiks

2 answers 2

I do not pretend to be the absolute truth, but from the school curriculum of mathematics one can recall problems about speed, time and distance (S = V * t). In the case of mp3, the distance is the file size, time is obviously sound time, and the bitrate is nothing more than the speed of the stream. Therefore, you can do the following:

  • find the source path from the audio.src property;

  • request the source using the HEAD method, among other things, we get the file size in bytes (Content-Length header), let it be S;

  • find out the time of sounding in seconds from the audio.duration property, let it be t;

  • According to the formula V = S / t, we get an approximate flow rate in bytes per second (we also have a file header and tags, they also take up space);

  • Dividing the obtained value by 128 (V = V / 1024 * 8) we obtain the flow rate in kilobits per second.

  • 2
    It will not work if a large album cover is attached to the mp3-file - andreymal
  • I agree, therefore, wrote that the calculations are approximate. - Serafim Prozorov
  • Thanks but already implemented, in the same way. But as it was supposed that something shows exactly, but somewhere there is a cover that adds weight and extra bitrate. In fact, these are just numbers .... - Freekazoid

mp3 files consist of small segments, so-called. frames (frames), and everyone can have their own bitrate and sample rate.

At the beginning of the frame is a header of 4 bytes:

 AAAAAAAA AAABBCCD EEEEFFGH IIJJKLMM 

The bit rate is written in E bits - the first 4 bits of the 3rd byte. See the link above for possible values.

There are several ways to read binary data in JS.

It remains to read all the frames and bitrate averaged? =)

Another option is to pull out on the server side all possible metadata about the file, and keep them, say, in a .json file with the same name as mp3.

You can pull out, for example, using the ffprobe utility.