forked from Stinkstudios/sono
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwaveform.js
More file actions
63 lines (53 loc) · 1.77 KB
/
waveform.js
File metadata and controls
63 lines (53 loc) · 1.77 KB
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
import sono from '../core/sono';
function waveform() {
let buffer,
wave;
return function(audioBuffer, length) {
if (!window.Float32Array || !window.AudioBuffer) {
return [];
}
const sameBuffer = buffer === audioBuffer;
const sameLength = wave && wave.length === length;
if (sameBuffer && sameLength) {
return wave;
}
wave = new Float32Array(length);
if (!audioBuffer) {
return wave;
}
// cache for repeated calls
buffer = audioBuffer;
const chunk = Math.floor(buffer.length / length),
resolution = 5, // 10
incr = Math.max(Math.floor(chunk / resolution), 1);
let greatest = 0;
for (let i = 0; i < buffer.numberOfChannels; i++) {
// check each channel
const channel = buffer.getChannelData(i);
for (let j = 0; j < length; j++) {
// get highest value within the chunk
for (let k = j * chunk, l = k + chunk; k < l; k += incr) {
// select highest value from channels
let a = channel[k];
if (a < 0) {
a = -a;
}
if (a > wave[j]) {
wave[j] = a;
}
// update highest overall for scaling
if (a > greatest) {
greatest = a;
}
}
}
}
// scale up
const scale = 1 / greatest;
for (let i = 0; i < wave.length; i++) {
wave[i] *= scale;
}
return wave;
};
}
export default sono.register('waveform', waveform, sono.utils);