-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaudio.js
113 lines (98 loc) · 2.68 KB
/
audio.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
// vim: set sw=4:ts=4:
// BufferLoader adapted from: http://www.html5rocks.com/en/tutorials/webaudio/intro/js/buffer-loader.js
class BufferLoader {
constructor(context, urlList, callback) {
this.context = context;
this.urlList = urlList;
this.onload = callback;
this.bufferList = new Array();
this.loadCount = 0;
}
loadBuffer(url, index) {
// Load buffer asynchronously
const request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";
const loader = this;
request.onload = function () {
// Asynchronously decode the audio file data in request.response
loader.context.decodeAudioData(
request.response,
function (buffer) {
if (!buffer) {
alert("error decoding file data: " + url);
return;
}
loader.bufferList[index] = buffer;
if (++loader.loadCount == loader.urlList.length)
loader.onload(loader.bufferList);
},
function (error) {
console.error("decodeAudioData error", error);
}
);
};
request.onerror = function () {
throw Error("BufferLoader: XHR error");
};
request.send();
}
load() {
for (let i = 0; i < this.urlList.length; ++i)
this.loadBuffer(this.urlList[i], i);
}
}
/*
* AudioLibrary
* Represents a collection of playable audio samples
*/
class AudioLibrary {
constructor(samples) {
this.samples = samples;
this.ready = false;
this.audioContext =
new AudioContext() || WebkitAudioContext() || MozAudioContext();
const urls = this.samples.map((f) => "samples/" + f.file);
const self = this;
const bufferLoader = new BufferLoader(this.audioContext, urls, function (
buffers
) {
for (let i = 0; i < buffers.length; i++) {
self.samples[i].buffer = buffers[i];
}
self.ready = true;
});
bufferLoader.load();
}
getCurrentTime() {
return this.audioContext.currentTime;
}
getSampleBuffer(name) {
const sample = this.samples.find(function (s) {
return s.name == name;
});
if (!sample) {
throw Error("Sample not found: " + name);
}
return sample.buffer;
}
playSampleAfter(name, time) {
const buffer = this.getSampleBuffer(name);
const source = this.audioContext.createBufferSource();
source.buffer = buffer;
source.connect(this.audioContext.destination);
if (!source.start) {
source.start = source.noteOn;
}
source.start(time);
}
stopAll() {
this.audioContext.suspend();
}
resumeAll() {
this.audioContext.resume();
}
restart() {
this.audioContext = new AudioContext();
}
}