-
Notifications
You must be signed in to change notification settings - Fork 1
/
Sound.ts
143 lines (111 loc) · 3.16 KB
/
Sound.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
/**
* Created by MSI on 04.01.2017.
*/
import {m} from "./Math";
declare var Howl:any;
const SOUND_PATH = 'sound/';
const MUSIC_PATH = 'music/';
type LazyLoadRequest = {
cb: Function
}
export class Sound {
constructor() {
}
private sounds: Object;
private _enabled:boolean = true;
private loaded:number = 0;
private total:number = 0;
private musicInstanceName:string;
private musicInstance:any = null;
public ready:boolean = false;
public soundsPlaying: Array<any> = [];
public loadingCallbacks: Array<any> = [];
public get enabled() {
return this._enabled;
}
public set enabled(e) {
this._enabled = e;
}
lazyPlayMusic(fullName: string, volume: number = null, pos: number = null): any {
this.loadOneSound(MUSIC_PATH + fullName, (sound) => {
this.play(null, sound, true, volume);
});
}
lazyPlaySound(fullName: string): any {
this.loadOneSound(SOUND_PATH + fullName, (sound) => {
this.play(null, sound);
})
}
stopAll(){
for (let x of this.soundsPlaying) {
x.stop()
}
this.loadingCallbacks = [];
}
loadOneSound(s: string, cb: Function): void{
let noExt = s.split("/").pop().replace(/\.[^/.]+$/, "");
noExt = noExt.toLowerCase();
let sound = new Howl({
src: s,
autoplay: false,
loop: false,
volume: 1,
});
this.sounds[noExt] = sound;
this.sounds[noExt].once('load', () => {
cb(sound);
});
}
load(musicAssets:Array<string>, soundAssets:Array<string>, cb:Function) {
this.sounds = {};
let c = 0;
for (let x of musicAssets) {
this.loadOneSound(MUSIC_PATH + x, function(){
c ++;
if (c == soundAssets.length + musicAssets.length) {
cb();
}
})
}
for (let x of soundAssets) {
this.loadOneSound(SOUND_PATH + x, function(){
c ++;
if (c == soundAssets.length + musicAssets.length) {
cb();
}
})
}
if (c == soundAssets.length + musicAssets.length) {
cb();
}
}
playMusic(snd:string): any {
return this.play(snd, null, true);
}
unmute() {
Howl.unmute(false);
}
mute() {
Howl.mute(true);
}
playRandom(arr: string[]){
this.play(m.getRand(arr))
}
play(snd: string, sndObj: any = null, loop: boolean =false, volume: number = null): any {
if (!this.enabled) return;
try {
let soundObj = sndObj ? sndObj : this.sounds[snd.toLowerCase()];
if (volume)
soundObj.volume(volume);
soundObj.loop(loop);
soundObj.play();
this.soundsPlaying.push(soundObj);
soundObj.once('end', () => {
this.soundsPlaying.splice(this.soundsPlaying.indexOf(soundObj) , 1);
});
return soundObj;
} catch (e) {
}
return null
};
}