2019-04-20 16:02:41 -05:00
|
|
|
import {Trait} from '@avocado/entity';
|
|
|
|
|
2019-04-21 23:01:29 -05:00
|
|
|
import {Sound} from '..';
|
|
|
|
|
2019-04-20 16:02:41 -05:00
|
|
|
export class Audible extends Trait {
|
|
|
|
|
|
|
|
static defaultParams() {
|
|
|
|
return {
|
|
|
|
sounds: {},
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2019-05-05 04:26:35 -05:00
|
|
|
static type() {
|
|
|
|
return 'audible';
|
|
|
|
}
|
|
|
|
|
2019-04-20 16:02:41 -05:00
|
|
|
hydrate() {
|
|
|
|
this.loadSounds();
|
|
|
|
}
|
|
|
|
|
2019-05-06 04:03:43 -05:00
|
|
|
constructor(entity, params, state) {
|
|
|
|
super(entity, params, state);
|
2019-05-04 14:06:47 -05:00
|
|
|
this._sounds = this.params.sounds;
|
2019-04-20 16:02:41 -05:00
|
|
|
this.sounds = {};
|
|
|
|
}
|
|
|
|
|
|
|
|
destroy() {
|
|
|
|
for (const key in this.sounds) {
|
|
|
|
const sound = this.sounds[key];
|
2019-04-21 23:01:29 -05:00
|
|
|
sound.release();
|
2019-04-20 16:02:41 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
loadSounds() {
|
2019-04-21 23:01:29 -05:00
|
|
|
const keys = Object.keys(this._sounds);
|
|
|
|
const soundPromises = [];
|
|
|
|
for (let i = 0; i < keys.length; i++) {
|
|
|
|
const key = keys[i];
|
2019-04-20 16:02:41 -05:00
|
|
|
const soundJSON = this._sounds[key];
|
2019-04-21 23:01:29 -05:00
|
|
|
soundPromises.push(Sound.load(soundJSON.uri));
|
2019-04-20 16:02:41 -05:00
|
|
|
}
|
2019-04-21 23:01:29 -05:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
});
|
2019-04-20 16:02:41 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
methods() {
|
|
|
|
return {
|
|
|
|
|
|
|
|
hasSound: (key) => {
|
|
|
|
return !!this.sounds[key];
|
|
|
|
},
|
|
|
|
|
|
|
|
playSound: (key) => {
|
|
|
|
const sound = this.sounds[key];
|
|
|
|
if (!sound) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
sound.play();
|
|
|
|
},
|
|
|
|
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|