-
Notifications
You must be signed in to change notification settings - Fork 0
/
soundbrix_v3.js
364 lines (358 loc) · 13.5 KB
/
soundbrix_v3.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/*
Copyright 2018 Jaycliff Arcilla of Eversun Software Philippines Corporation (Davao branch)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
SoundBrix: Experimental HTML5 Sound Object Creation Library powered by Web Audio API (Version 1.3 - 06/30/2014)
Author: Jaycliff Arcilla
NOTE(S):
- AudioScheduledSourceNode.onended fires when it has literally finished the playback, yes that means even when deliberately stopped via the stop() method
- create silence -> SOUNDBRIX.ctx.createBuffer(2, SOUNDBRIX.ctx.sampleRate * sound.audioBuffer().duration, SOUNDBRIX.ctx.sampleRate)
*/
/*global AudioContext, AudioBuffer*/
/*jslint browser: true, devel: true, nomen: true, unparam: true, sub: true, regexp: true */
var SOUNDBRIX = (function (AudioContext, max) {
"use strict";
var ctx = new AudioContext(),
masterGain = ctx.createGain(),
noop = Function.prototype,
hasOwnProperty = Object.prototype.hasOwnProperty;
masterGain.gain.setValueAtTime(1, ctx.currentTime);
masterGain.connect(ctx.destination);
function getSettings(us) {
var key, ds = {
type: 'multishot',
playbackRate: 1,
volume: 1
};
for (key in us) {
if (hasOwnProperty.call(us, key)) {
ds[key] = us[key];
}
}
return ds;
}
// loadSound creates garbage
function loadSound(url, callback) {
var request = new XMLHttpRequest();
// Load the sound asynchronously ('true' means asynchronous)
// Synchronous operations in JavaScript are greatly discouraged
request.open('GET', url, true);
request.responseType = 'arraybuffer';
request.onload = function () {
callback(request.response);
};
request.send();
}
function toString() {
return 'function ' + this.name + '() { [native code] }';
}
function Multishot(settings) {
var that = this,
playing = false,
vol = settings.volume,
playbackRate = settings.playbackRate,
internalAudioBuffer = settings.audioBuffer instanceof AudioBuffer ? settings.audioBuffer : null,
gainNode = ctx.createGain(),
internalListOfBSN = [],
sourceURL = settings.src || settings.href || settings.source || settings.url || settings.location;
gainNode.connect(masterGain);
this.getGainNode = function getGainNode() {
return gainNode;
};
this.getType = function getType() {
return settings.type;
};
this.getDuration = function getDuration() {
if (internalAudioBuffer) {
return internalAudioBuffer.duration;
}
return 0;
};
this.audioBuffer = function audioBuffer(ab) {
if (arguments.length) {
internalAudioBuffer = ab;
return that;
}
return internalAudioBuffer;
};
this.volume = function volume(value) {
if (typeof value !== "number") {
throw new TypeError('parameter must be a number');
}
if (arguments.length > 0) {
vol = value;
return that;
}
return vol;
};
this.isReady = function isReady() {
return !!internalAudioBuffer;
};
this.isPlaying = function isPlaying() {
return playing;
};
function onended() {
internalListOfBSN.shift();
if (internalListOfBSN.length === 0) {
playing = false;
(settings.onend || noop).call(this);
}
//console.log(this === internalListOfBSN.shift());
}
this.play = function play() {
var bsNode = ctx.createBufferSource(), currentTime = ctx.currentTime;
if (internalAudioBuffer) {
bsNode.buffer = internalAudioBuffer;
//bsNode.loop = settings.loop;
//bsNode.detune.setValueAtTime(-1200, ctx.currentTime);
bsNode.playbackRate.setValueAtTime(playbackRate, currentTime);
bsNode.onended = onended;
bsNode.connect(gainNode);
bsNode.start(currentTime);
internalListOfBSN.push(bsNode);
if (!playing) {
playing = true;
(settings.onplay || noop).call(this);
}
}
return that;
};
this.stop = function stop() {
var k, len, bsn;
if (internalAudioBuffer && playing) {
playing = false;
for (k = 0, len = internalListOfBSN.length; k < len; k += 1) {
bsn = internalListOfBSN[k];
bsn.onended = null;
bsn.stop();
}
internalListOfBSN.length = 0;
(settings.onstop || noop).call(this);
}
return that;
};
if (!internalAudioBuffer) {
loadSound(
sourceURL,
function (response) {
ctx.decodeAudioData(
response,
function success(buffer) {
internalAudioBuffer = buffer;
setTimeout((settings.onload || noop), 0);
},
function fail() {
throw new Error('Failed to load source from ' + sourceURL);
}
);
}
);
} else {
setTimeout((settings.onload || noop), 0);
}
}
function Loop(settings) {
var that = this,
playing = false,
breakLoop = false,
playTimerID = 0,
isPlayTimerSet = false,
vol = settings.volume,
playbackRate = settings.playbackRate,
internalAudioBuffer = settings.audioBuffer instanceof AudioBuffer ? settings.audioBuffer : null,
gainNode = ctx.createGain(),
currentBSN = null,
nextBSN = null,
nextPlaybackTime = 0,
sourceURL = settings.src || settings.href || settings.source || settings.url || settings.location;
gainNode.connect(masterGain);
this.getGainNode = function getGainNode() {
return gainNode;
};
this.getType = function getType() {
return settings.type;
};
this.getDuration = function getDuration() {
if (internalAudioBuffer) {
return internalAudioBuffer.duration;
}
return 0;
};
this.audioBuffer = function audioBuffer(ab) {
if (arguments.length) {
internalAudioBuffer = ab;
return that;
}
return internalAudioBuffer;
};
this.volume = function volume(value) {
if (typeof value !== "number") {
throw new TypeError('parameter must be a number');
}
if (arguments.length) {
vol = value;
return that;
}
return vol;
};
this.isReady = function isReady() {
return !!internalAudioBuffer;
};
this.isPlaying = function isPlaying() {
return playing;
};
this.isWaiting = function isWaiting() {
return isPlayTimerSet;
};
function onended() {
if (!breakLoop) {
nextPlaybackTime += internalAudioBuffer.duration;
currentBSN = nextBSN;
nextBSN = ctx.createBufferSource();
nextBSN.buffer = internalAudioBuffer;
nextBSN.playbackRate.setValueAtTime(playbackRate, ctx.currentTime);
nextBSN.onended = onended;
nextBSN.connect(gainNode);
nextBSN.start(nextPlaybackTime);
(settings.onloop || noop).call(this, nextPlaybackTime);
} else {
breakLoop = false;
nextPlaybackTime = 0;
playing = false;
currentBSN = null;
(settings.onstop || noop).call(this);
}
}
this.nextLoopTime = function nextLoopTime() {
return nextPlaybackTime;
};
function playEventTimerCallback() {
playing = true;
isPlayTimerSet = false;
(settings.onplay || noop).call(this, nextPlaybackTime);
}
this.play = function play(specificTime) {
var currentTime = ctx.currentTime, startTime = 0, timeout = 0;
if (arguments.length > 0) {
if (typeof specificTime !== "number") {
throw new TypeError('parameter must be a number');
}
} else {
specificTime = 0;
}
if (internalAudioBuffer && !playing && !isPlayTimerSet) {
startTime = max(specificTime, currentTime);
nextPlaybackTime = startTime + internalAudioBuffer.duration;
currentBSN = ctx.createBufferSource();
currentBSN.buffer = internalAudioBuffer;
currentBSN.playbackRate.setValueAtTime(playbackRate, startTime);
currentBSN.onended = onended;
currentBSN.connect(gainNode);
currentBSN.start(startTime);
nextBSN = ctx.createBufferSource();
nextBSN.buffer = internalAudioBuffer;
nextBSN.playbackRate.setValueAtTime(playbackRate, startTime);
nextBSN.onended = onended;
nextBSN.connect(gainNode);
nextBSN.start(nextPlaybackTime);
timeout = max(0, (specificTime - currentTime) * 1000);
if (timeout === 0) {
playing = true;
(settings.onplay || noop).call(this, nextPlaybackTime);
} else {
playTimerID = setTimeout(playEventTimerCallback, timeout);
isPlayTimerSet = true;
(settings.onwait || noop).call(this, startTime);
}
}
return that;
};
// 'end' basically stops the loop, but waits for the current sound to finish playing
this.end = function end() {
if (internalAudioBuffer && playing || isPlayTimerSet) {
breakLoop = true;
nextBSN.onended = null;
nextBSN.stop(0);
nextBSN = null;
}
return that;
};
function resetBSNs() {
nextPlaybackTime = 0;
currentBSN.onended = null;
currentBSN.stop(0);
currentBSN = null;
if (!breakLoop) {
nextBSN.onended = null;
nextBSN.stop(0);
nextBSN = null;
} else {
breakLoop = false;
}
}
this.stop = function stop() {
if (internalAudioBuffer && playing) {
playing = false;
resetBSNs();
(settings.onstop || noop).call(this);
} else if (isPlayTimerSet) {
clearTimeout(playTimerID);
isPlayTimerSet = false;
resetBSNs();
(settings.onwaitcancel || noop).call(this);
}
return that;
};
if (!internalAudioBuffer) {
loadSound(
sourceURL,
function (response) {
ctx.decodeAudioData(
response,
function success(buffer) {
internalAudioBuffer = buffer;
setTimeout((settings.onload || noop), 0);
},
function fail() {
throw new Error('Failed to load source from ' + sourceURL);
}
);
}
);
} else {
setTimeout((settings.onload || noop), 0);
}
}
Multishot.toString = toString;
Loop.toString = toString;
toString.toString = toString;
return {
createSound: function createSound(userSettings) {
var settings;
if (typeof userSettings !== "object") {
throw new TypeError('parameter must be a plain object');
}
settings = getSettings(userSettings);
switch (settings.type) {
case 'multishot':
return new Multishot(settings);
case 'loop':
return new Loop(settings);
default:
return null;
}
},
ctx: ctx,
context: ctx,
masterGain: masterGain
};
}((typeof AudioContext === "function" && AudioContext) || window.AudioContext || window.webkitAudioContext, Math.max));