3

I'd like to use indexedDB to store an audio file which I get from my CDN - to improve the users experience, and also do not put such heavy loads onto my CDN. Is this generally recommended for files like mp3? Are there any gotchas?

I've found a few tutorials on storing audio & image in indexedDb, but I also looked for answers on here before, and here somebody says that indexedDB is not generally recommended to store audio files. - Is this true? Unfortunately, the person does not give any further explanation. So if this is true, I'd like to know why.

Thanks a lot.

userjmillohara
  • 457
  • 5
  • 25

1 Answers1

4

You can store binary data in IndexedDB but need to be careful for platform limitations.

The main platform limit I know of is described in this Best Practices article by a Google Engineer - the naive approach of storing a Blob type won't work on iOS - you need to convert to an ArrayBuffer using a pair of functions:

function blobToArrayBuffer(blob) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.addEventListener('loadend', (e) => {
      resolve(reader.result);
    });
    reader.addEventListener('error', reject);
    reader.readAsArrayBuffer(blob);
  });
}

function arrayBufferToBlob(buffer, type) {
  return new Blob([buffer], {type: type});
}

Many warnings against storage come from the (incorrect) assumption you have to convert data to base-64 encoded ASCII, which is slow and bloats the amount of spaces needed.

Andy Dent
  • 17,578
  • 6
  • 88
  • 115