Javascript DataView read ID3 Tags

1.1k views Asked by At

I am trying to read the ID3 tags of an music file. Currently i have a Dataview object with the last 128 bits of an audio file in it (because the ID3 tags are at the last 128 bits in a audio file). So at this point i don't know how i go further, how can i read the different part (title, album etc.) from the audio file? (Please dont answer with external scripts or library)

window.onload = function(){
  file = $("file");
  reader = new FileReader();
  reader.onload = function(){
    length = reader.result.byteLength
    dv = new DataView(reader.result, length-128, 128);
  }
  file.onchange = function(e){
    reader.readAsArrayBuffer(e.target.files[0]);
  }
}
1

There are 1 answers

1
Mohamed El-Sayed On

Please check the structure of ID3 tag format (https://en.wikipedia.org/wiki/ID3#Layout) , this is the format for v1:

    | Field  | Offset | Length | Value   |
    |--------|--------|--------|---------|
    | Header | 0      | 3      | TAG     |
    | Title  | 3      | 30     |         |
    | Artist | 33     | 30     |         |
    | ... ect                            |
  1. Read 128 bytes from the file into a blob.
  2. Create a reader to read the Blob.
  3. Create a DataView to read the ArrayBuffer.
  4. For each field, convert the buffer into a string with String.fromCharCode.

function readString(dataView, offset, length) {
  var o = '';
  for (var i = offset; i < offset + length; i++) {
    // keep only printable characters
    if (i >= 32) o += String.fromCharCode(dataView.getUint8(i));
  }
  return o;
}
var file = fileElm.files[0];
var blob = file.slice(file.size - 128, file.size);
var reader = new FileReader();
reader.onload = function(evt) {
  var buff = evt.target.result;
  var dataView = new DataView(buff)
  console.log('TAG:', readString(dataView, 0, 3));
  console.log('title: ', readString(dataView, 3, 30)); // title
  console.log('artist: ', readString(dataView, 33, 30)); // artist
  console.log('album: ', readString(dataView, 63, 30)); // album
  console.log('year: ', readString(dataView, 93, 4)); // year
}
reader.readAsArrayBuffer(blob);