-
Notifications
You must be signed in to change notification settings - Fork 20
/
index.js
78 lines (60 loc) · 2.09 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
var AudioContext = window.AudioContext || window.webkitAudioContext
module.exports = WebAudioAnalyser
function WebAudioAnalyser(audio, ctx, opts) {
if (!(this instanceof WebAudioAnalyser)) return new WebAudioAnalyser(audio, ctx, opts)
if (!(ctx instanceof AudioContext)) (opts = ctx), (ctx = null)
opts = opts || {}
this.ctx = ctx = ctx || new AudioContext
if (!(audio instanceof AudioNode)) {
audio = (audio instanceof Audio || audio instanceof HTMLAudioElement)
? ctx.createMediaElementSource(audio)
: ctx.createMediaStreamSource(audio)
}
this.analyser = ctx.createAnalyser()
this.stereo = !!opts.stereo
this.audible = opts.audible !== false
this.wavedata = null
this.freqdata = null
this.splitter = null
this.merger = null
this.source = audio
if (!this.stereo) {
this.output = this.source
this.source.connect(this.analyser)
if (this.audible)
this.analyser.connect(ctx.destination)
} else {
this.analyser = [this.analyser]
this.analyser.push(ctx.createAnalyser())
this.splitter = ctx.createChannelSplitter(2)
this.merger = ctx.createChannelMerger(2)
this.output = this.merger
this.source.connect(this.splitter)
for (var i = 0; i < 2; i++) {
this.splitter.connect(this.analyser[i], i, 0)
this.analyser[i].connect(this.merger, 0, i)
}
if (this.audible)
this.merger.connect(ctx.destination)
}
}
WebAudioAnalyser.prototype.waveform = function(output, channel) {
if (!output) output = this.wavedata || (
this.wavedata = new Uint8Array((this.analyser[0] || this.analyser).frequencyBinCount)
)
var analyser = this.stereo
? this.analyser[channel || 0]
: this.analyser
analyser.getByteTimeDomainData(output)
return output
}
WebAudioAnalyser.prototype.frequencies = function(output, channel) {
if (!output) output = this.freqdata || (
this.freqdata = new Uint8Array((this.analyser[0] || this.analyser).frequencyBinCount)
)
var analyser = this.stereo
? this.analyser[channel || 0]
: this.analyser
analyser.getByteFrequencyData(output)
return output
}