avocado-old/packages/sound/traits/audible.trait.js
2019-05-04 14:06:47 -05:00

66 lines
1.2 KiB
JavaScript

import {Trait} from '@avocado/entity';
import {Sound} from '..';
export class Audible extends Trait {
static defaultParams() {
return {
sounds: {},
};
}
hydrate() {
this.loadSounds();
}
initialize() {
this._sounds = this.params.sounds;
this.sounds = {};
}
destroy() {
for (const key in this.sounds) {
const sound = this.sounds[key];
sound.release();
}
}
loadSounds() {
const keys = Object.keys(this._sounds);
const soundPromises = [];
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const soundJSON = this._sounds[key];
soundPromises.push(Sound.load(soundJSON.uri));
}
const soundsPromise = Promise.all(soundPromises);
soundsPromise.then((sounds) => {
for (let i = 0; i < sounds.length; i++) {
const key = keys[i];
const sound = sounds[i];
this.sounds[key] = sound;
}
});
}
methods() {
return {
hasSound: (key) => {
return !!this.sounds[key];
},
playSound: (key) => {
const sound = this.sounds[key];
if (!sound) {
return;
}
sound.play();
},
};
}
}