fix: sound

This commit is contained in:
cha0s 2021-02-03 16:24:16 -06:00
parent ac04dae473
commit 8e4fea8c66
2 changed files with 29 additions and 27 deletions

View File

@ -1,6 +1,7 @@
import {Howl} from 'howler';
import {join} from 'path';
import {JsonResource} from '@avocado/resource';
import {JsonResource, Resource} from '@avocado/resource';
import {Howl} from 'howler';
export default () => class Sound extends JsonResource {
@ -11,9 +12,7 @@ export default () => class Sound extends JsonResource {
}
destroy() {
if (this.sound) {
this.sound.unload();
}
this.sound?.unload();
}
async load(json = {}) {
@ -21,14 +20,21 @@ export default () => class Sound extends JsonResource {
const {interval = 0, volume = 1} = json;
this.interval = interval;
this.originalVolume = volume;
this.sound = new Howl(json);
await new Promise((resolve) => {
this.sound.once('load', resolve);
});
if (json.src && json.src.length > 0) {
const mappedSources = json.src.map((src) => join(Resource.root, src));
this.sound = new Howl({src: mappedSources});
this.sound.volume(volume);
// await new Promise((resolve, reject) => {
// this.sound.once('load', () => {
// resolve();
// });
// this.sound.once('loaderror', reject);
// });
}
}
play() {
if (this.interval > 0 && this.timestamp > 0) {
if (this.sound && this.interval > 0 && this.timestamp > 0) {
if ((Date.now() - this.timestamp) < this.interval) {
const volume = this.sound.volume(this.handle);
this.sound.volume(

View File

@ -52,24 +52,16 @@ export default (latus) => class Audible extends Trait {
});
}
async extendJson(json) {
const extended = await super.extendJson(json);
if (this.params.sounds && 'client' === process.env.SIDE) {
const {Sound} = latus.get('%resources');
extended.sounds = Object.fromEntries(
await Promise.all(
Object.entries(this.params.sounds)
.map(async ([key, sound]) => [key, await Sound.load(sound.uri)]),
),
);
}
return extended;
}
async load(json) {
await super.load(json);
if (json.sounds) {
this.#sounds = json.sounds;
if (this.params.sounds && 'client' === process.env.SIDE) {
const {Sound} = latus.get('%resources');
this.#sounds = Object.fromEntries(
await Promise.all(
Object.entries(this.params.sounds)
.map(async ([key, sound]) => [key, await Sound.load(sound)]),
),
);
}
}
@ -78,7 +70,11 @@ export default (latus) => class Audible extends Trait {
hasSound: (key) => !!this.#sounds[key],
playSound: (key) => this.entity.hasSound(key) && this.#sounds[key].play(),
playSound: (key) => {
if (this.entity.hasSound(key)) {
this.#sounds[key].play();
}
},
};
}