playcanvas
Version:
Open-source WebGL/WebGPU 3D engine for the web
77 lines (76 loc) • 1.72 kB
JavaScript
import { path } from "../../core/path.js";
import { http, Http } from "../../platform/net/http.js";
import { Sound } from "../../platform/sound/sound.js";
import { ResourceHandler } from "./handler.js";
const supportedExtensions = [
".ogg",
".mp3",
".wav",
".mp4a",
".m4a",
".mp4",
".aac",
".opus"
];
class AudioHandler extends ResourceHandler {
constructor(app) {
super(app, "audio");
this.manager = app.soundManager;
}
_isSupported(url) {
const ext = path.getExtension(url);
return supportedExtensions.indexOf(ext) > -1;
}
load(url, callback) {
if (typeof url === "string") {
url = {
load: url,
original: url
};
}
const success = function(resource) {
callback(null, new Sound(resource));
};
const error = function(err) {
let msg = `Error loading audio url: ${url.original}`;
if (err) {
msg += `: ${err.message || err}`;
}
console.warn(msg);
callback(msg);
};
if (this._createSound) {
if (!this._isSupported(url.original)) {
error(`Audio format for ${url.original} not supported`);
return;
}
this._createSound(url.load, success, error);
} else {
error(null);
}
}
_createSound(url, success, error) {
const manager = this.manager;
if (!manager.context) {
error("Audio manager has no audio context");
return;
}
const options = {
retry: this.maxRetries > 0,
maxRetries: this.maxRetries
};
if (url.startsWith("blob:") || url.startsWith("data:")) {
options.responseType = Http.ResponseType.ARRAY_BUFFER;
}
http.get(url, options, (err, response) => {
if (err) {
error(err);
return;
}
manager.context.decodeAudioData(response, success, error);
});
}
}
export {
AudioHandler
};