-
Notifications
You must be signed in to change notification settings - Fork 0
/
Web Audio API Test.js
54 lines (46 loc) · 1.26 KB
/
Web Audio API Test.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
var audioContext = new AudioContext();
var scheduledBuffers = [];
window.createBuffer = function(path) {
let source = audioContext.createBufferSource();
let request = new Request(path);
fetch(request)
.then(data => { return data.arrayBuffer() })
.then(buffer => {
audioContext.decodeAudioData(buffer, function(decodedData) {
source.buffer = decodedData;
source.connect(audioContext.destination);
}, function(error) {
console.log(error);
})
});
return source;
}
window.playSound = function(buffer, time) {
if (time) {
buffer.start(time);
scheduledBuffers.push(buffer);
let timeToPlay = time - audioContext.currentTime;
setTimeout(() => {
scheduledBuffers = scheduledBuffers.filter(currentBuffer => {return currentBuffer != buffer});
} ,timeToPlay * 1000);
} else {
buffer.start(0);
}
}
window.stopPlayback = function() {
scheduledBuffers.forEach(buffer => {
buffer.stop();
});
scheduledBuffers = [];
}
// class BufferSound {
// constructor(name, buffer) {
// this.name = name;
// this.buffer = buffer;
// }
// }
// let kick = createBuffer("Sounds/kick.mp3", "Kick");
// savedBuffers.addBuffer(kick);
// window.addEventListener('keydown', function() {
// playSound(kick.buffer);
// });