-
Notifications
You must be signed in to change notification settings - Fork 2
/
audioengine.js
268 lines (236 loc) · 7.2 KB
/
audioengine.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
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
// audioengine.js
// Simple utility wrapper around some Web Audio API features to be able to
// quickly build applications which play sound using the Web Audio API.
// To use this functions include audioengine.js and use the AudioManager "am"
// variable like:
// am = initAudioManager();
// am.playSoundFromURL("http://sound.org/example.ogg")
// am.setMainVolume(0.5)
// If playing a sound which was already played in the future, the AudioManager
// object will keep the buffer and reuse the data.
var audioengine_verbose = false;
function log(message) {
if (audioengine_verbose){
console.log(message)
}
}
// "Private" interface (don't use these methods directly outside audioengine.js)
const recbufferLen = 4096;
var rec = undefined;
function startAudioContext(){
context = new (window.AudioContext || window.webkitAudioContext)();
if (!context.createGain)
context.createGain = context.createGainNode;
context.gainNode = context.createGain();
if (!context.createScriptProcessor) {
context.recNode = context.createJavaScriptNode(recbufferLen, 2, 0);
} else {
context.recNode = context.createScriptProcessor(recbufferLen, 2, 0);
}
context.gainNode.connect(context.destination);
rec = new Recorder(context.gainNode, { // init recorder
bufferLen: recbufferLen
})
}
function playBuffer(buffer, time, options) {
const source = context.createBufferSource();
source.buffer = buffer;
connected = false;
if (options !== undefined){
if (options.loop) {
source.loop = options.loop;
}
if (options.onended) {
source.onended = options.onended;
}
if (options.panHRTF) {
const panner = context.createPanner();
panner.panningModel = "HRTF"
panner.distanceModel = "inverse"
panner.setPosition(options.panHRTF.x, options.panHRTF.y, options.panHRTF.z);
source.connect(panner);
panner.connect(context.gainNode);
connected = true;
}
}
if (!connected){
// If source was not connected to master gain node because of options, connect now
source.connect(context.gainNode);
}
source.start(time);
return source;
}
function loadSounds(obj, soundMap, callback) {
// Array-ify
var names = [];
var paths = [];
for (var name in soundMap) {
var path = soundMap[name];
names.push(name);
paths.push(path);
}
bufferLoader = new BufferLoader(context, paths, function(bufferList) {
for (var i = 0; i < bufferList.length; i++) {
var buffer = bufferList[i];
var name = names[i];
obj[name] = buffer;
}
if (callback) {
callback();
}
});
bufferLoader.load();
}
function BufferLoader(context, urlList, callback) {
this.context = context;
this.urlList = urlList;
this.onload = callback;
this.bufferList = new Array();
this.loadCount = 0;
}
BufferLoader.prototype.loadBuffer = function(url, index) {
// Load buffer asynchronously
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";
var loader = this;
request.onload = function() {
// Asynchronously decode the audio file data in request.response
loader.context.decodeAudioData(
request.response,
function(buffer) {
if (!buffer) {
log('Error decoding file data: ' + url);
return;
}
loader.bufferList[index] = buffer;
if (++loader.loadCount == loader.urlList.length)
loader.onload(loader.bufferList);
},
function(error) {
log('DecodeAudioData error: ' + error);
}
);
}
request.onerror = function() {
log('BufferLoader: XHR error');
}
request.send();
};
BufferLoader.prototype.load = function() {
for (var i = 0; i < this.urlList.length; ++i)
this.loadBuffer(this.urlList[i], i);
};
// Public interface (AudioManager object)
var AudioManager = function() {};
AudioManager.prototype.loadSound = function(url, onLoadedCallback) {
log('Loading: ' + url);
var name = url; // Use URL to identify the sound in pool
var soundMap = {}
soundMap[name] = url
loadSounds(this, soundMap, function(){
onLoadedCallback(name);
});
}
var BUFFER_NODES = [];
AudioManager.prototype.playBufferByName = function(name, time, options) {
log('Playing: ' + name);
if (time === undefined){ time = 0; }
if (name in this){
var buffer_node = playBuffer(this[name], time, options);
BUFFER_NODES.push({name: name, node: buffer_node})
} else {
log('Error: "' + name + '" buffer not loaded!')
}
}
AudioManager.prototype.getBufferList = function(value) {
var buffers = [];
for(var key in this){
if (this[key] instanceof AudioBuffer){
buffers.push(key);
}
}
return buffers;
}
AudioManager.prototype.playSoundFromURL = function(url, time, options) {
if (time === undefined){ time = 0; }
if (url in this){ // If sound is already loaded, just play it
AudioManager.prototype.playBufferByName(url, time, options);
} else { // If sound has not been loaded, load it and play afterwards
AudioManager.prototype.loadSound(url, function(){
AudioManager.prototype.playBufferByName(url, time, options);
})
}
}
AudioManager.prototype.setMainVolume = function(value) {
// value should be in range [0, 1]
if (value > 1.0){
value = 1.0;
} else if (value < 0){
value = 0.0;
}
context.gainNode.gain.value = value;
}
AudioManager.prototype.stopAllBufferNodes = function(disableOnEnded, hardStop, removeBuffers) {
for(i=0; i<BUFFER_NODES.length; i++) {
if (disableOnEnded) {
BUFFER_NODES[i].node.onended = undefined; // Set onended call to undefined just in case it is set
}
if (hardStop) {
BUFFER_NODES[i].node.stop();
}
}
BUFFER_NODES = [];
if (removeBuffers){
var bufferList = this.getBufferList();
for (i in bufferList){
this[bufferList[i]] = undefined; // remove actual buffer data from audio manager
}
}
}
AudioManager.prototype.stopBufferNodesForSound = function(name, disableOnEnded, hardStop, removeBuffer) {
log('Removing buffer nodes for sound: ' + name);
NEW_BUFFER_NODES = [];
for (i in BUFFER_NODES){
if (BUFFER_NODES[i].name !== name){
NEW_BUFFER_NODES.push(BUFFER_NODES[i]);
} else {
if (disableOnEnded){
BUFFER_NODES[i].node.onended = undefined; // Set onended call to undefined just in case it is set
}
if (hardStop){
BUFFER_NODES[i].node.stop();
}
}
}
BUFFER_NODES = NEW_BUFFER_NODES;
if (removeBuffer){
this[name] = undefined; // remove actual buffer data from audio manager
}
}
AudioManager.prototype.getAllUniqueBufferNodesList = function(value) {
var keys = [];
for (var item in BUFFER_NODES){
var key = BUFFER_NODES[item].name;
if (keys.indexOf(key) === -1){
keys.push(key);
}
}
return keys;
}
AudioManager.prototype.startRecording = function () {
rec.record();
}
AudioManager.prototype.stopRecording = function (downloadFilename) {
rec.stop();
rec.exportWAV(function (audioBlob){
Recorder.forceDownload(audioBlob, downloadFilename);
rec.clear();
});
}
// Initialize things
function initAudioManager(){
log('Initializing audio context and audio manager')
startAudioContext();
return new AudioManager();
}