-
Notifications
You must be signed in to change notification settings - Fork 0
/
sound.js
30 lines (26 loc) · 829 Bytes
/
sound.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
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();
var sounds = {};
function loadSound(name, url) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
request.onload = function() {
context.decodeAudioData(request.response, function(buffer) {
sounds[name] = buffer;
});
}
request.send();
}
function playSound(buffer, volume = 1, panx = 0) {
var source = context.createBufferSource();
var gain = context.createGain();
var pan = context.createPanner();
source.buffer = buffer;
source.connect(gain);
gain.connect(pan);
pan.connect(context.destination);
gain.gain.value = volume;
pan.setPosition(panx, 0, 0);
source.start(0);
}