-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathsound.js
97 lines (92 loc) · 2.53 KB
/
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
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
function Sound() {
var soundDir = "assets/sound/";
var musicDir = "assets/music/";
var tracks = [
"silk-way.webm",
"dawn.webm",
"rain-from-the-night-sky.webm",
"celtic-forest.webm",
"aquarel.webm",
]
this.tracks = [];
this.sounds = [];
if (document.location.hash.indexOf("mute") != -1) {
game.config.sound.playMusic = false;
game.config.sound.playSound = false;
return;
}
this.tracks = tracks.map(function(name) {
var audio = new Audio(musicDir + name);
audio.addEventListener('ended', function(e) {
this.playMusic();
}.bind(this));
return audio;
}.bind(this));
var sounds = ["beep.ogg", "chop.webm"];
sounds.forEach(function(name) {
var audio = new Audio(soundDir + name);
name = name.split(".").slice(0, -1).join(".")
this.sounds[name] = audio;
}.bind(this));
}
Sound.prototype = {
trackIndex: 0,
track: null,
tracks: [],
sounds: {},
playMusic: function() {
if (!game.config.sound.playMusic)
return;
if (this.track == null || ++this.trackIndex >= this.tracks.length) {
this.trackIndex = 0;
}
this.track = this.tracks[this.trackIndex];
if (this.track.played.length > 0) {
this.track.load();
}
this.track.play();
},
toggleMusic: function() {
if (this.track)
this.stopMusic()
else
this.playMusic();
},
stopMusic: function() {
if (!this.track)
return;
if (this.track.paused)
this.track.play()
else
this.track.pause();
},
playSound: function(name, repeat) {
if (!game.config.sound.playSounds)
return;
this.stopSound(name);
var sound = this.sounds[name];
if (!sound) {
console.warn("Sound " + name + " not found");
return;
}
sound.onloadeddata = function() {
sound.currentTime = 0
sound.play();
};
sound.load();
if (repeat !== undefined) {
repeat = repeat || 1000;
sound.repeat = setTimeout(this.playSound.bind(this, name, repeat), repeat);
}
},
stopSound: function(name) {
var sound = this.sounds[name];
if (!sound)
return;
sound.pause();
if (sound.repeat) {
clearTimeout(sound.repeat);
sound.repeat = null;
}
},
}