71 lines
1.3 KiB
JavaScript
71 lines
1.3 KiB
JavaScript
import {Trait} from '@avocado/entity';
|
|
|
|
import {Sound} from '..';
|
|
|
|
export class Audible extends Trait {
|
|
|
|
static defaultParams() {
|
|
return {
|
|
sounds: {},
|
|
};
|
|
}
|
|
|
|
static type() {
|
|
return 'audible';
|
|
}
|
|
|
|
hydrate() {
|
|
this.loadSounds();
|
|
}
|
|
|
|
constructor(entity, params, state) {
|
|
super(entity, params, state);
|
|
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();
|
|
},
|
|
|
|
};
|
|
}
|
|
|
|
}
|