-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
52 lines (45 loc) · 1.71 KB
/
index.ts
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
const fs = require("fs");
const { decode } = require("wav-decoder");
const inputFile = "file_example_WAV_10MG (1).wav";
const desiredMaxValue = 10;
const desiredLength = 120;
async function generateWaveformDataArray() {
try {
const buffer = fs.readFileSync(inputFile);
const audioData = await decode(buffer);
const { channelData, sampleRate } = audioData;
const audioDuration = channelData[0].length / sampleRate; // Duration in seconds
let windowSizeMs = Math.ceil((audioDuration / desiredLength) * 1000); // Adjust window size based on desired length
const samplesPerWindow = Math.floor(sampleRate * (windowSizeMs / 1000));
const waveformDataArray = [];
for (let i = 0; i < channelData[0].length; i += samplesPerWindow) {
let sum = 0;
for (let j = 0; j < samplesPerWindow; j++) {
if (i + j < channelData[0].length) {
sum += Math.abs(channelData[0][i + j]);
}
}
const average = sum / samplesPerWindow;
waveformDataArray.push(average);
}
const maxValue = Math.max(...waveformDataArray);
const scaledWaveformDataArray = waveformDataArray.map(
(value) => (value / maxValue) * desiredMaxValue
);
return { scaledWaveformDataArray, sampleRate };
} catch (error) {
console.error("Error:", error);
}
}
generateWaveformDataArray()
.then(({ scaledWaveformDataArray, sampleRate }) => {
// Save text file with scaled waveform data
fs.writeFileSync(
"waveform_data.txt",
scaledWaveformDataArray.join("\n"),
"utf8"
);
console.log("Scaled Waveform Data Array:", scaledWaveformDataArray);
console.log("Sample Rate:", sampleRate);
})
.catch((error) => console.error("Error:", error));