-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
125 lines (105 loc) · 2.61 KB
/
index.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
114
115
116
117
118
119
120
121
122
123
124
125
var Emitter = require('emitter');
module.exports = Analyzer;
/**
* WebAudio analyzer.
*
* @param {Context} ctx
* @return {Analyzer}
* @api public
*/
function Analyzer(ctx, opts) {
if (!(this instanceof Analyzer)) return new Analyzer(ctx, opts);
if (!opts) opts = {};
this.ctx = ctx;
this.processor = ctx.createJavaScriptNode(1024);
this.processor.onaudioprocess = this.process.bind(this);
this.analyzers = {};
this.smoothing = opts.smoothing || 0;
this.resume();
}
Emitter(Analyzer.prototype);
/**
* Analyze `node`.
*
* @param {String} name
* @param {AudioNode} node
* @param {Number=} channel
* @return {Analyzer}
* @api public
*/
Analyzer.prototype.add = function(name, node, channel) {
var analyzer = this.ctx.createAnalyser();
analyzer.fftSize = 2048;
analyzer.smoothingTimeConstant = this.smoothing;
if (Object.keys(this.analyzers).length == 0) node.connect(this.processor);
node.connect(analyzer, channel || 0);
this.analyzers[name] = analyzer;
return this;
};
/**
* Resume analyzing.
*
* @return {Analyzer}
* @api public
*/
Analyzer.prototype.resume = function() {
this.processor.connect(this.ctx.destination);
return this;
};
/**
* Pause analyzing.
*
* @return {Analyzer}
* @api public
*/
Analyzer.prototype.pause = function() {
this.processor.disconnect();
return this;
};
/**
* Onaudioprocess callback.
*
* @api private
*/
Analyzer.prototype.process = function() {
var analyzers = this.analyzers;
if (this.listeners('float frequency data').length) {
var channels = {};
each(analyzers, function(analyzer, name) {
var chunk = new Float32Array(analyzer.frequencyBinCount);
analyzer.getFloatFrequencyData(chunk);
channels[name] = chunk;
});
this.emit('float frequency data', channels);
}
if (this.listeners('byte frequency data').length) {
var channels = {};
each(analyzers, function(analyzer, name) {
var chunk = new Uint8Array(analyzer.frequencyBinCount);
analyzer.getByteFrequencyData(chunk);
channels[name] = chunk;
});
this.emit('byte frequency data', channels);
}
if (this.listeners('byte time domain data').length) {
var channels = {};
each(analyzers, function(analyzer, name) {
var chunk = new Uint8Array(analyzer.fftSize);
analyzer.getByteTimeDomainData(chunk);
channels[name] = chunk;
});
this.emit('byte time domain data', channels);
}
};
/**
* Object iteration utility.
*
* @param {Object} obj
* @param {Function} fn
* @api private
*/
function each(obj, fn) {
Object.keys(obj).forEach(function(key) {
fn(obj[key], key);
});
}