-
Notifications
You must be signed in to change notification settings - Fork 6
/
mic.js
52 lines (42 loc) · 1.29 KB
/
mic.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
var mic = (function() {
var context;
var microphone;
var filter;
var analyzer;
var listener;
navigator.getUserMedia =navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
var audiocontext = window.AudioContext || window.webkitAudioContext;
var onStream = function(stream) {
microphone = context.createMediaStreamSource(stream);
analyser = context.createAnalyser();
microphone.connect(analyser);
requestAnimationFrame(analyze);
};
var onError = function(e) {
console.error('No microphone!');
};
var analyze = function() {
var data = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteTimeDomainData(data);
for(var i = 0; i < data.length; i++) {
listener(data[i]-128);
}
requestAnimationFrame(analyze);
};
var listen = function(callback) {
listener = (typeof callback === 'function') ? callback : null;
if (listener) {
context = new audiocontext();
context.createGain = context.createGainNode;
context.createDelay = context.createDelayNode;
context.createScriptProcessor = context.createJavaScriptNode;
navigator.getUserMedia( {audio: true}, onStream, onError);
} else {
throw new Error("Listener callback not defined");
}
}
return {listen:listen}
})();