userjmillohara
userjmillohara

Reputation: 467

Using indexedDB to Cache Audio Files Not Recommended?

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.

Upvotes: 3

Views: 2799

Answers (1)

Andy Dent
Andy Dent

Reputation: 17971

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 (actually redirects here and do not mention what is written further) 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});
}

Safari problem was mentioned in old 2019-02-12 article

And bugs on Safari 11 and 12 are marked as fixed:
https://bugs.webkit.org/show_bug.cgi?id=188438
https://bugs.webkit.org/show_bug.cgi?id=198278

Many warnings against storage come from the (incorrect) assumption you have to convert data to base-64 encoded ASCII, which is slow (this is actually very fast compared to repeating the download duration from the web that counts not in less than ms, but in seconds) and bloats the amount of space needed (only about 33–37%).

Upvotes: 4

Related Questions