-
Notifications
You must be signed in to change notification settings - Fork 2
/
audio-peak.ts
99 lines (87 loc) · 2.41 KB
/
audio-peak.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
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
export class AudioPeak {
private audioCtx = new AudioContext();
/**
*
* @param audioUrl audio url
* @param cutSeconds high music seconds
* @param precision return peaks width (1 seconds / precision), higher is more accurate
*/
public async get(
audioUrl: string,
cutSeconds: number,
precision = 10
): Promise<{
cutSeconds: number;
precision: number;
startTime: number;
peaks: number[];
audioBuffer: AudioBuffer;
}> {
const response = await fetch(audioUrl);
if (response.status >= 400) {
throw new Error(`response.status: ${response.status}`);
}
const audioData = await response.arrayBuffer();
const audioBuffer = await this.audioCtx.decodeAudioData(audioData);
const channelData = audioBuffer.getChannelData(0);
const peaks = AudioPeak.getPeaks(
precision * parseInt(`${audioBuffer.duration + 1}`, 10),
channelData
);
const startTime = AudioPeak.findMaxIndex(peaks, cutSeconds * precision) / precision;
return {
cutSeconds,
precision,
startTime,
peaks,
audioBuffer,
};
}
public static accumulate(arr: number[]) {
let sum = 0;
for (let i = 0, l = arr.length; i < l; i += 1) {
sum += arr[i];
}
return sum;
}
public static findMaxIndex(arr: number[], k: number) {
let sum = AudioPeak.accumulate(arr.slice(0, k));
let res = sum;
let index = 0;
for (let i = k; i < arr.length; i += 1) {
sum += arr[i] - arr[i - k];
if (sum >= res) {
res = sum;
index = i - k;
}
}
return index;
}
public static getMaxInRange(array: Float32Array, start: number, end: number) {
let max = 0;
let max1 = 0;
let current: number;
const step = parseInt(`${(end - start) / 15}`, 10);
for (let i = start; i < end; i += step) {
current = Math.abs(array[i]);
if (current > max) {
max1 = max;
max = current;
}
}
return (max + max1) / 2;
}
public static getPeaks(width: number, data: Float32Array): number[] {
const dataLength = data.length;
const size = dataLength / width;
let current = 0;
const peaks = new Array(width);
for (let i = 0; i < width; i += 1) {
const start = parseInt(`${current}`, 10);
current += size;
const end = parseInt(`${current}`, 10);
peaks[i] = AudioPeak.getMaxInRange(data, start, end);
}
return peaks;
}
}