-
-
Notifications
You must be signed in to change notification settings - Fork 41
/
sound.js
94 lines (80 loc) · 2.75 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
let SFX_OW1 = 0;
let SFX_WIND = 1;
window.sfx = new Array(1000);
window.sound = new Array(1000);
let SoundStation = function(filename)
{
this.that = this;
this.context = null;
this.audio = new Audio(filename);
// this.volumeGain = null; // currently used only for background music volume
this.volumeGainContext = null; // currently used only for background music volume
this.musicVolume = 1.0;
let that = this;
// Play sound in __buffer_ID
this.play = function(__buffer_ID, repeatSound, contextGain) {
// To turn all sounds off, uncomment this line:
// return false;
if (window.sfx[__buffer_ID] == undefined)
return;
let __buffer = window.sfx[__buffer_ID];
let source = this.context.createBufferSource();
source.buffer = __buffer;
// tie to gain context so we can control this sound's volume
if (contextGain)
{
this.volumeGainContext = this.context.createGain();
source.connect(this.volumeGainContext);
this.volumeGainContext.connect(this.context.destination);
this.volumeGainContext.gain.value = 1.0;
} else
// do regular connect (full volume)
source.connect(this.context.destination);
source.start(0);
if (repeatSound)
source.loop = true;
}
this.available = false;
// call this function from your program entry point to intitialize
this.Initialize = function() {
let contextClass = (window.AudioContext ||
window.webkitAudioContext ||
window.mozAudioContext ||
window.oAudioContext ||
window.msAudioContext);
if (contextClass) {
this.available = true;
this.context = new contextClass();
LoadSfx();
} else
this.available = false;
}
this.onError = function() { console.log("Sound.load('" + filename_url + "')... Failed!"); }
// Load sound into __buffer_ID from URL (full-path required)
this.load = function(__buffer_ID, filename_url) {
let request = new XMLHttpRequest();
request.open('GET', filename_url, true);
request.responseType = 'arraybuffer';
let that_v2 = this.that;
request.onload = function() {
that_v2.context.decodeAudioData(request.response, function(theBuffer) {
window.sfx[__buffer_ID] = theBuffer;
//" + filename_url + "
console.log("Sound.load('mp3')... Ok!");
// if (filename_url == "http://www.learnjquery.org/games/gem/sfx/delune.mp3")
window.soundtrackReady = true;
}, this.onError);
}
request.send();
}
}
// Load sound resources into buffer index locations
function LoadSfx() {
console.log("LoadSfx()...");
Sound.load(0, website.url + "/sfx/jewel9.mp3");
Sound.load(1, website.url + "/sfx/jewel2.mp3");
Sound.load(2, website.url + "/sfx/swoosh.mp3");
// ... etc (mp3 must be available @ URL)
}
// initialize sound station
let Sound = new SoundStation();