avocado-old/packages/sound/traits/audible.trait.js

105 lines
1.8 KiB
JavaScript
Raw Normal View History

2019-04-20 16:02:41 -05:00
import {Trait} from '@avocado/entity';
2019-04-21 23:01:29 -05:00
import {Sound} from '..';
2020-06-15 17:26:20 -05:00
export default class Audible extends Trait {
2019-04-20 16:02:41 -05:00
2020-06-19 17:59:14 -05:00
static behaviorContextTypes() {
2020-06-19 15:31:35 -05:00
return {
2020-06-19 22:01:45 -05:00
hasSound: {
type: 'bool',
label: 'Has $1 sound',
args: [
['key', {
type: 'string',
}],
],
},
2020-06-19 15:31:35 -05:00
playSound: {
type: 'void',
label: 'Play the $1 sound.',
args: [
['key', {
type: 'string',
}],
],
},
};
}
2019-04-20 16:02:41 -05:00
static defaultParams() {
return {
sounds: {},
};
}
2020-06-19 22:01:45 -05:00
static describeParams() {
return {
sounds: {
type: 'object',
label: 'Sounds',
},
};
}
2019-05-05 04:26:35 -05:00
static type() {
return 'audible';
}
2019-04-20 16:02:41 -05:00
hydrate() {
2019-09-29 13:19:57 -05:00
if (AVOCADO_CLIENT) {
this.loadSounds();
}
2019-04-20 16:02:41 -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();
},
};
}
}