diff --git a/src/track/loader/FetchLoader.js b/src/track/loader/FetchLoader.js new file mode 100644 index 00000000..689fe6eb --- /dev/null +++ b/src/track/loader/FetchLoader.js @@ -0,0 +1,18 @@ +import Loader from "./Loader"; + +export default class extends Loader { + /** + * Loads an audio file via fetch API. + */ + load() { + return new Promise((resolve, reject) => { + fetch(this.src) + .then((data) => data.arrayBuffer()) + .then((arrayBuffer) => super.fetchLoad(arrayBuffer)) + .then((decodedAudio) => resolve(decodedAudio)) + .catch((err) => { + reject(Error(`Track ${this.src} failed to load with error: ${err}`)); + }); + }); + } +} diff --git a/src/track/loader/Loader.js b/src/track/loader/Loader.js index 14793440..e3c6a7f1 100644 --- a/src/track/loader/Loader.js +++ b/src/track/loader/Loader.js @@ -57,4 +57,28 @@ export default class { ); }); } + + fetchLoad(arrayBuffer) { + this.setStateChange(STATE_DECODING); + + return new Promise((resolve, reject) => { + this.ac.decodeAudioData( + arrayBuffer, + (audioBuffer) => { + this.audioBuffer = audioBuffer; + this.setStateChange(STATE_FINISHED); + + resolve(audioBuffer); + }, + (err) => { + if (err === null) { + // Safari issues with null error + reject(Error("MediaDecodeAudioDataUnknownContentType")); + } else { + reject(err); + } + } + ); + }); + } } diff --git a/src/track/loader/LoaderFactory.js b/src/track/loader/LoaderFactory.js index 5541436c..310bfc14 100644 --- a/src/track/loader/LoaderFactory.js +++ b/src/track/loader/LoaderFactory.js @@ -1,6 +1,7 @@ import BlobLoader from "./BlobLoader"; import IdentityLoader from "./IdentityLoader"; import XHRLoader from "./XHRLoader"; +import FetchLoader from "./FetchLoader"; export default class { static createLoader(src, audioContext, ee) { @@ -9,7 +10,8 @@ export default class { } else if (src instanceof AudioBuffer) { return new IdentityLoader(src, audioContext, ee); } else if (typeof src === "string") { - return new XHRLoader(src, audioContext, ee); + //return new XHRLoader(src, audioContext, ee); + return new FetchLoader(src, audioContext, ee); } throw new Error("Unsupported src type");