-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
251 lines (211 loc) · 7.71 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
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
require('dotenv').config();
const fft = require('fft-js').fft;
const fftUtil = require('fft-js').util;
const linear = require('everpolate').linear;
const fs = require('fs');
const WaveFile = require('wavefile').WaveFile;
const { unpackArray } = require('byte-data');
const { createCanvas, loadImage } = require('canvas');
const MAX_FREQUENCY = 26000; // 22 kHz highest frequency a human can hear. In order to make the spectrogram 128px we go pass that value.
const samplesLength = 256; // must be dividable by 2: 2^10=1024, 44100 samples/s => ~1m, 16ms
const pngWidth = 128; //px of segments
/**
* FFT analysis on given samples
* @param samples
* @return {{magnitudes, frequencies}|{joined: Uint8Array | BigInt64Array | {magnitude: *, frequency: any}[] | Float64Array | Int8Array | Float32Array | Int32Array | Uint32Array | Uint8ClampedArray | BigUint64Array | Int16Array | Uint16Array, magnitudes, frequencies}}
*/
function analyzeSamples(samples) {
const phasers = fft(samples);
const frequencies = fftUtil.fftFreq(phasers, 44100); // Sample rate and coef is just used for length, and frequency step
const magnitudes = fftUtil.fftMag(phasers);
return { frequencies, magnitudes }
};
/**
* Create a specter and populate it with the frequencies and magnitudes for the given samples
* @param samples
* @return Interpolated specter
*/
function spectro(samples) {
const C0 = 16.35; // lowest piano note
const NEXT_NOTE_MULTIPLIER = Math.pow(2, 1 / 12); // notes 16,25 = C0, C0 * 2^(1/12) = C# ...
const { frequencies, magnitudes } = analyzeSamples(samples);
let spectro = [];
for (let i = C0; i <= MAX_FREQUENCY; i = i * NEXT_NOTE_MULTIPLIER) {
spectro.push(i)
}
spectro = linear(spectro, frequencies, magnitudes);
return spectro;
};
/**
* Returns the number of sample sets at a sample size
* @param wav
* @return {number}
*/
const getNumberOfSamples = (wav) => {
return Math.floor(wav.data.samples.length / (samplesLength * (wav.f.h / 8)));
};
/**
* Return the sample at a given index.
* @param {any} wav: the wave file
* @param {number} startIndex The sample start index.
* @param {number} stopIndex The sample stop index.
* @return {number} The sample.
* @throws {Error} If the sample index is off range.
*/
const getSamples = (wav, startIndex, stopIndex) => {
startIndex = startIndex * (wav.f.h / 8);
stopIndex = stopIndex * (wav.f.h / 8);
if (stopIndex + wav.f.h / 8 > wav.data.samples.length) {
const errMsg = `Range error, stopIndex ${stopIndex}, stopIndex + wav.dataType.bits ${stopIndex + wav.f.h}, wav.data.samples.length ${wav.data.samples.length}`;
throw new Error(errMsg);
}
return unpackArray(
wav.data.samples.slice(startIndex, stopIndex),
{ bits: wav.f.h, fp: wav.f.R, signed: wav.f.O, be: wav.f.o } // TODO MAKE SURE FILE DATA TYPE IS CORRECT!
);
};
const readWav = (file, callback) => {
let wav;
// read the wav file
const filePath = './audio-files/' + file;
fs.readFile(filePath, (err, buffer) => {
if (err) {
return callback(err);
}
wav = new WaveFile(buffer);
wav.toBitDepth("32f"); // convert to 32f for fft
return callback(file, wav)
})
};
const processWav = (fileName, wav, options = {}) => {
let index = 0;
let maxIndex;
if (options.maxSamples) {
maxIndex = options.maxSamples
} else {
maxIndex = getNumberOfSamples(wav) - 1;
}
const spectrogram = [];
do {
const samples = getSamples(wav, index * samplesLength, (index + 1) * samplesLength);
index++;
const snapshot = spectro(samples);
spectrogram.push(snapshot);
} while (index < maxIndex);
drawSpectrogram(fileName, spectrogram)
// let fileIndex = 0
// let spectrogramSegment = []
// for (let i = 1; i < spectrogram.length; i++) {
// const sequence = spectrogram[i];
// spectrogramSegment.push(sequence)
// if (i && i % pngWidth == 0) {
// const currentFileName = fileName.split('.').join('-' + fileIndex + '.')
// fileIndex++
// drawSpectrogram(currentFileName, spectrogramSegment)
// spectrogramSegment = []
// }
// }
};
function drawSpectrogram(fileName, spectrograph) {
const strokeHeight = 1;
const canvasHeight = spectrograph[0].length * strokeHeight;
const canvasWidth = spectrograph.length;
const canvas = createCanvas(canvasWidth, canvasHeight);
const ctx = canvas.getContext('2d');
// init canvas
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
let maxValue = 0
let minValue = 100000000000
spectrograph.forEach((sequence, timeSeq) => {
sequence.forEach((value, frequency) => {
if (frequency > 110) value = 0
let hue = 0; // for maximum magnitude of 150 k = 1,35
let sat = '0%';
let lit = (value > 100 ? 100 : value) + '%'; //100 is selected as the maximum possible magnitude
if (value > maxValue) {
maxValue = value
} else if (value < minValue) {
minValue = value
}
ctx.beginPath();
ctx.strokeStyle = `hsl(${hue}, ${sat}, ${lit})`;
ctx.moveTo(timeSeq, canvasHeight - (frequency * strokeHeight));
ctx.lineTo(timeSeq, canvasHeight - (frequency * strokeHeight + strokeHeight));
ctx.stroke();
});
});
const outPath = './audio-files/' + fileName.replace('.wav', '.png')
const out = fs.createWriteStream(outPath);
const stream = canvas.createPNGStream();
stream.pipe(out);
out.on('finish', (err) => {
if (err) { return callback(err); }
console.log('The PNG file was created.')
});
};
function readPNGSpectrogram(fileName) {
const filePath = './audio-files/' + fileName
loadImage(filePath)
.then((image) => {
const imgHeight = image.height
const imgWidth = image.width
const canvas = createCanvas(imgWidth, imgHeight);
const ctx = canvas.getContext('2d');
ctx.drawImage(image, 0, 0);
const imageData = ctx.getImageData(0, 0, imgWidth, imgHeight).data
const splitPixels = []
for (let i = 0; i < imageData.length; i += 4) {
const pixel = imageData.slice(i, i + 4);
splitPixels.push(pixel);
}
const pixels = splitPixels.map(RGBToHSL)
console.table(pixels)
})
.catch(err => {
console.log('oh no!', err)
})
}
function RGBToHSL(pixel) {
// Make r, g, and b fractions of 1
let [r, g, b, a] = pixel
r /= 255;
g /= 255;
b /= 255;
a /= 255;
// Find greatest and smallest channel values
let cmin = Math.min(r, g, b)
let cmax = Math.max(r, g, b)
let delta = cmax - cmin
let h = 0
let s = 0
let l = 0
// Calculate hue
// No difference
if (delta == 0)
h = 0;
// Red is max
else if (cmax == r)
h = ((g - b) / delta) % 6;
// Green is max
else if (cmax == g)
h = (b - r) / delta + 2;
// Blue is max
else
h = (r - g) / delta + 4;
h = Math.round(h * 60);
// Make negative hues positive behind 360°
if (h < 0)
h += 360;
// Calculate lightness
l = (cmax + cmin) / 2;
// Calculate saturation
s = delta == 0 ? 0 : delta / (1 - Math.abs(2 * l - 1));
// Multiply l and s by 100
s = +(s * 100).toFixed(1);
l = +(l * 100).toFixed(1);
return "hsl(" + h + "," + s + "%," + l + "%)";
}
// readPNGSpectrogram('heart-beat-137135.png')
readWav('bkvhi.wav', processWav) //Transforms .wav file into .png spectrogram
//hsl(199, 100%, 50%)
//0, 127, 192, 255(Alpha)