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(); }, }; } }