-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwav-spectrogram.js
More file actions
196 lines (118 loc) · 5.21 KB
/
wav-spectrogram.js
File metadata and controls
196 lines (118 loc) · 5.21 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
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
/****************************************************************************
* wav-spectrogram.js
* pcprince.co.uk
* September 2018
*****************************************************************************/
'use strict';
/* jslint plusplus: true */
const dsp = require('dsp.js-browser');
const decode = require('audio-decode');
const colormap = require('colormap');
function scaleAcrossRange (x, max, min) {
return (x - min) / (max - min);
}
function median(values) {
values.sort((a, b) => {
return a - b;
});
const half = Math.floor(values.length / 2);
if (values.length % 2) {
return values[half];
}
return (values[half - 1] + values[half]) / 2.0;
}
function medianFilter(array) {
const filteredArray = [];
for (let i = 1; i < array.length - 1; i++) {
const filteredRow = [];
for (let j = 1; j < array[i].length - 1; j++) {
const values = [];
values.push(array[i - 1][j], array[i][j], array[i + 1][j]);
values.push(array[i - 1][j - 1], array[i][j - 1], array[i + 1][j - 1]);
values.push(array[i - 1][j + 1], array[i][j + 1], array[i + 1][j + 1]);
filteredRow.push(median(values));
}
filteredArray.push(filteredRow);
}
return filteredArray;
}
function drawSpectrogram(params, callback) {
const arrayBuffer = params.arrayBuffer;
const canvasElem = params.canvasElem;
const cmap = params.cmap;
const nfft = params.nfft || 512;
const frameLengthMs = params.frameLengthMs || 0.1;
const frameStepMs = params.frameStepMs || 0.005;
decode(arrayBuffer, (err, audioBuffer) => {
if (err || audioBuffer.length === 0) {
console.error('Failed to load file');
typeof params.errorHandler === 'function' && params.errorHandler();
return;
}
// Extract samples from audio file
const sampleRate = audioBuffer.sampleRate;
const samples = audioBuffer.getChannelData(0);
let sampleArray = Array.prototype.slice.call(samples);
const frameLength = frameLengthMs * sampleRate;
const frameStep = frameStepMs * sampleRate;
// Pad signal to make sure that all frames have equal number of samples without truncating any samples from the original signal
const numFrames = Math.ceil((samples.length - frameLength) / frameStep);
const paddedArrayLength = numFrames * frameStep + frameLength;
sampleArray = sampleArray.concat(new Array(paddedArrayLength - samples.length).fill(0));
const frames = [];
for (let i = 0; i < numFrames; i++) {
const frameStart = i * frameStep;
const frame = [];
for (let j = 0; j < frameLength; j++) {
const frameIndex = j + frameStart;
// Apply Hamming filter
const filteredSample = sampleArray[frameIndex] * (0.54 - (0.46 * Math.cos(2.0 * Math.PI * j / (frameLength - 1.0))));
frame.push(filteredSample);
}
frames.push(frame);
}
let maxValue = 0;
let minValue = 0;
let spectrumFrames = [];
for (let m = 0; m < frames.length; m++) {
// Apply FFT
const fft = new dsp.RFFT(nfft, sampleRate);
fft.forward(frames[m]);
const spectrum = [];
for (let n = 0; n < fft.trans.length; n++) {
if (fft.trans[n] !== 0) {
spectrum.push(Math.log(Math.abs(fft.trans[n])));
} else {
// Prevent log(0) = -inf
spectrum.push(0);
}
}
spectrumFrames.push(spectrum);
}
// Apply median filter
spectrumFrames = medianFilter(spectrumFrames);
// Calculate range of filtered values to scale colours between
for (let a = 0; a < spectrumFrames.length; a++) {
maxValue = Math.max(Math.max.apply(null, spectrumFrames[a]), maxValue);
minValue = Math.min(Math.min.apply(null, spectrumFrames[a]), minValue);
}
const ctx = canvasElem.getContext('2d');
// Scale drawing context to fill canvas
const specWidth = spectrumFrames.length;
const specHeight = spectrumFrames[0].length / 2;
ctx.scale(canvasElem.width / specWidth, canvasElem.height / specHeight);
// Create colourmap to map spectrum values to colours
const colours = colormap({colormap: cmap, nshades: 255, format: 'hex'});
for (let o = 0; o < spectrumFrames.length; o++) {
// Ignore half of spectrogram above Nyquist frequency as it is redundant a reflects values below
for (let p = spectrumFrames[0].length / 2; p < spectrumFrames[0].length; p++) {
// Scale values between 0 - 255 to match colour map
const scaledValue = Math.round(255 * scaleAcrossRange(spectrumFrames[o][p], maxValue, minValue));
ctx.fillStyle = colours[scaledValue];
ctx.fillRect(o, p - spectrumFrames[0].length / 2, 1, 1);
}
}
typeof callback === 'function' && callback();
});
}
exports.drawSpectrogram = drawSpectrogram;