This repository has been archived by the owner on Mar 8, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
soundlib.js
85 lines (73 loc) · 2.24 KB
/
soundlib.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
var SoundLib = SoundLib || {};
SoundLib = function()
{
this.sounds = {};
}
SoundLib.prototype.loadSound = function(sound) {
this.sounds[sound.name] = sound;
}
SoundLib.prototype.playSound = function(b) {
var src = ac.createBufferSource();
src.buffer = b;
src.connect(ac.destination);
src.start(0);
}
SoundLib.loadDir = function(file) {
var reader = new FileReader();
reader.readAsText(file);
console.log(reader);
}
SoundLib.sound = function(name, source) {
window.AudioContext = window.AudioContext || window.webkitAudioContext;
this.ac = new AudioContext();
this.name = name;
this.source = source;
this.audioBuffer;
}
SoundLib.sound.prototype.play = function(volume, delay) {
var loaded = false,
volume = volume || 1,
delay = delay || 0;
window.AudioContext = window.AudioContext || window.webkitAudioContext;
window.ac = new AudioContext();
window.destinationNode = window.ac.destination;
var play = function() {
if(loaded) {
var sourceNode = ac.createBufferSource();
sourceNode.buffer = bufferedSound;
var volumeNode = ac.createGain();
volumeNode.gain.value = volume;
sourceNode.connect(volumeNode);
volumeNode.connect(destinationNode);
sourceNode.start(delay);
}
};
var bufferedSound;
var req = new XMLHttpRequest();
req.open('GET', this.source, true);
req.responseType='arraybuffer';
req.onload=function(){
ac.decodeAudioData(req.response,function(buffer){
bufferedSound=buffer;
loaded = true;
this.buffer = ac.createBufferSource(buffer, true);
play();
}, function(err) {
console.error('decodeAudioData error', err);
});
};
req.send();
}
SoundLib.sound.prototype.getBuffer = function() {
var ac = this.ac,
self = this;
var req = new XMLHttpRequest();
req.open('GET', self.source, true);
req.onload = function() {
ac.decodeAudioData(req.response, function(buffer) {
self.audioBuffer = buffer;
console.log(self.audioBuffer);
});
};
req.send();
}