This repository has been archived by the owner on Aug 5, 2020. It is now read-only.
/
sounds.js
102 lines (78 loc) · 2.03 KB
/
sounds.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
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var Sound = {
muted: false,
isSupported: !!window.AudioContext
};
Sound.play = (function() {
// configs
var STEP_TIME = 10;
var OSCILLATOR_TYPES = {
sine: 0,
square: 1,
sawtooth: 2,
triangle: 3
};
// make "real audio" contexts too
var audios = [];
// make our master context
// sadly, there can only be one
var context;
if (Sound.isSupported)
context = new AudioContext;
return function playSound(options) {
// bail, bail!
if (Sound.muted)
return;
// this whole thing is in a try/catch because not everything
// supports this stuff
try {
// if it's a string, let's just run that file
if (typeof options === 'string') {
// find an available stream
var stream = audios.filter(function(audio) {
return audio.paused == true;
})[0];
// add a stream if we don't have one
if (!stream) {
stream = new Audio;
audios.push(stream);
}
// play it
stream.volume = 1;
stream.src = options;
stream.play();
return;
}
// make me an oscillator
var oscillator = context.createOscillator();
oscillator.connect(context.destination);
// parse the options
var type = options.type || 0;
var from = options.from || 440;
var to = options.to || from;
var duration = options.duration || 100;
// type?
// this isn't robust but screw it
if (typeof type === 'number')
oscillator.type = type;
else if (typeof type === 'string')
oscillator.type = OSCILLATOR_TYPES[type];
// start initial frequency
oscillator.frequency.value = from;
oscillator.noteOn(0);
// what's our tweening look like?
var stepSize = (to - from) / STEP_TIME;
// do the tweening
var interval = setInterval(function() {
oscillator.frequency.value += stepSize;
}, STEP_TIME);
// stop this noise
setTimeout(function() {
isPlaying = false;
oscillator.noteOff(0);
oscillator.disconnect();
clearInterval(interval);
}, duration);
} catch (e) {}
};
})();