forked from l0bster2/pocket-platformer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sound.js
43 lines (38 loc) · 927 Bytes
/
Sound.js
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
class Sound {
constructor(src, id = "", loop = false) {
this.sound = document.createElement("audio");
this.sound.src = src;
if(id) {
this.sound.id = id;
}
this.errorWhileLoading = false;
this.sound.loop = loop;
this.sound.setAttribute("preload", "auto");
this.sound.setAttribute("controls", "none");
this.sound.onloadeddata = () => this.loadedSrc()
this.sound.onerror = () => { this.errorWhileLoading = true; };
this.loaded = false;
this.sound.style.display = "none";
document.body.appendChild(this.sound);
}
loadedSrc() {
this.loaded = true;
}
stopAndPlay() {
if (this.loaded) {
this.sound.currentTime > 0 && this.sound.pause();
this.sound.currentTime = 0;
this.sound.play();
}
}
play() {
if (this.loaded) {
this.sound.play();
}
}
stop() {
if (this.loaded) {
this.sound.pause();
}
}
}