-
Notifications
You must be signed in to change notification settings - Fork 0
/
useVisualizer.js
266 lines (247 loc) · 11.4 KB
/
useVisualizer.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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
import { useEffect, useRef } from 'react'
import { easeInOutQuad } from 'wavemo/utils/math';
import { print } from 'wavemo/utils/print';
import { dynamicRepl, findRepeatedWords, isCSSColor } from 'wavemo/utils/check';
const useVisualizer = (audioRef, options, elements) => {
/*
options: {
minFreq: number,
maxFreq: number,
invisible: boolean,
quality: string, // "ultra" > "high" > "medium" > "low" > "verylow",
play: boolean,
logs: {
warn: boolean,
error: boolean,
info: boolean
}
}
elements: [
{
ref: useRef,
effects: [
{
type: string,
blending: number,
intensity: number,
color: string
}
]
}
]
*/
const defaults = {
color: 'white',
blending: 300,
intensity: 2,
minFreq: 0,
maxFreq: 1400,
quality: {
number: 512,
string: "medium"
},
logs: {
warn: true,
error: true,
info: true,
buffer: true
}
}
let _SHOW_WARN =
options.logs.warn != null &&
options.logs.warn == true ||
options.logs.warn == false ?
options.logs.warn :
defaults.logs.warn
let _SHOW_ERROR =
options.logs.error != null &&
options.logs.error == true ||
options.logs.error == false ?
options.logs.error :
defaults.logs.error
let _SHOW_INFO =
options.logs.info != null &&
options.logs.info == true ||
options.logs.info == false ?
options.logs.info :
defaults.logs.info
let _SHOW_BUFFER =
options.logs.buffer != null &&
options.logs.buffer == true ||
options.logs.buffer == false ?
options.logs.buffer :
defaults.logs.buffer
let clicked = false;
let audioContext;
const analyserRef = useRef(null);
useEffect(()=>{
if(audioRef.current) {
if (options.invisible && options.invisible == true) {
audioRef.current.style.height = '0'
audioRef.current.style.width = '0'
audioRef.current.style.opacity = '0'
}
}
document.addEventListener('click', ()=> {setupAudio()})
},[])
const setupAudio = async () => {
if (audioRef.current instanceof HTMLAudioElement) {
if (!audioContext) {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
}
if (!analyserRef.current) {
const analyser = audioContext.createAnalyser();
const source = audioContext.createMediaElementSource(audioRef.current);
source.connect(analyser);
analyser.connect(audioContext.destination);
if(!options.quality) {
print(_SHOW_WARN, "warn", `FFT_WARNING\nNO QUALITY PROPERTY SET\nDEFAULT QUALITY SET TO ${defaults.quality.string.toUpperCase()}`);
analyser.fftSize = defaults.quality.number
} else {
if(isNaN(options.quality)){
switch(options.quality) {
case "ultra":
analyser.fftSize = 8192;
break;
case "high":
analyser.fftSize = 2048;
break;
case "medium":
analyser.fftSize = 512;
break;
case "low":
analyser.fftSize = 128;
break;
default:
print(_SHOW_WARN, "warn", `FFT_WARNING\nNO QUALITY PROPERTY CONTAINS ${options.quality} AS AN OVERLOAD\nDEFAULT QUALITY SET TO ${defaults.quality.string.toUpperCase()}`);
analyser.fftSize = defaults.quality.number;
}
} else {
if (isPowerOfTwo(options.quality) && (Math.pow(2, 5) <= options.quality && options.quality <= Math.pow(2, 15))) {
analyser.fftSize = options.quality;
} else {
print(_SHOW_WARN, "warn", "FFT_WARNING\nQUALITY MUST BE POWER OF 2 BETWEEN 2^5 AND 2^15\n[32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768]\nDEFAULT QUALITY SET TO "+ defaults.quality);
analyser.fftSize = defaults.quality.number;
}
}
}
print(_SHOW_BUFFER, "log", `AUDIO_BUFFER_READY\nFFT_SIZE=${analyser.fftSize}\nSOURCE=${analyser ? 'CONNECTED' : 'ERR'}`);
analyserRef.current = analyser;
if(!audioRef.current) return print(_SHOW_ERROR, "error", 'AUDIO_ERR\nNO AUDIO FOUND TO PLAY\nSTOPPING...')
if(options.play && options.play == true)
if(audioRef.current.paused)
audioRef.current.play()
updateGradient();
}
}
if(!clicked) {
clicked = true;
elements.forEach((element, elementIndex) => {
if(!element.effects) return print(_SHOW_WARN, "warn", `ELEMENT_WARNING\nNO EFFECTS APPLIED AT ELEMENT[${elementIndex}]\nNO EFFECTS WILL BE APPLIED`)
if (!element.ref) return print(_SHOW_ERROR, "error", `ELEMENT_ERROR\nMISSING REF_PROP AT ELEMENT[${elementIndex}]\nNO REF TO APPLY EFFECTS`)
findRepeatedWords(element.effects, _SHOW_ERROR, elementIndex)
element.effects.forEach((effect, effectIndex) => {
if (!effect.blending) return print(_SHOW_WARN, "warn", `ELEMENT_WARNING\nNO BLENDING APPLIED AT ELEMENT[${elementIndex}].EFFECT[${effectIndex}]\nDEFAULT BLENDING IS ${defaults.blending}`)
let [firstWord, ...otherWords] = effect.type.split(' ');
switch(firstWord){
case "t-shadow":
case "b-shadow":
case "size":
case "f-size":
case "h":
case "w":
break;
case "custom":
print(_SHOW_INFO, "log", `EFFECT_INFO\nCUSTOM EFFECT APPLIED AT ELEMENT[${elementIndex}]\n${otherWords.join(' ')}`)
break;
default:
print(_SHOW_ERROR, "error", `EFFECT_ERROR\nEFFECT DOES NOT CONTAIN ${firstWord} AS OVERLOAD AT ELEMENT[${elementIndex}]\nNO EFFECTS WILL BE APPLIED`)
}
})
})
}
}
const updateGradient = () => {
const analyser = analyserRef.current;
if (analyser) {
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
analyser.getByteFrequencyData(dataArray);
// Filtra las frecuencias
const lowFrequencyData = dataArray.slice(
options.minFreq == null || isNaN(options.minFreq) ? defaults.minFreq : options.minFreq,
options.maxFreq == null || isNaN(options.maxFreq) ? defaults.maxFreq : options.maxFreq
);
// Calcule la intensidad promedio de las frecuencias bajas
const averageIntensity =
Array.from(lowFrequencyData).reduce((sum, value) => sum + value, 0) / lowFrequencyData.length;
// Interpola la intensidad con una función easeInOutQuad modificada
const easedIntensity = easeInOutQuad(averageIntensity / 255);
elements.forEach((element, index) => {
if(!element.ref.current) return;
if(!element.effects) return;
element.effects.forEach(effect => {
if(!effect) return;
let intensit = easedIntensity * (!effect.intensity || isNaN(effect.intensity) ? defaults.intensity : effect.intensity) ;
let [firstWord, ...otherWords] = effect.type.split(' ');
switch(firstWord) {
case "t-shadow":
element.ref.current.style.textShadow = `0 0 ${intensit}em ${!effect.color || !isCSSColor(effect.color) ? defaults.color : effect.color}`;
break;
case "b-shadow":
element.ref.current.style.boxShadow = `0 0 ${intensit}em ${!effect.color || !isCSSColor(effect.color) ? defaults.color : effect.color}`;
break;
case "size":
element.ref.current.style.width = `${intensit}em`;
element.ref.current.style.height = `${intensit}em`;
break;
case "h":
element.ref.current.style.height = `${intensit}em`;
break;
case "w":
element.ref.current.style.width = `${intensit}em`;
break;
case "f-size":
let fontSize = 16; // Default font size for other elements
switch(element.ref.current.tagName.toLowerCase()) {
case "p":
fontSize = 16;
break;
case "h1":
fontSize = 64;
break;
case "h2":
fontSize = 32;
break;
case "h3":
fontSize = 24;
break;
case "h4":
fontSize = 20;
break;
case "h5":
fontSize = 18;
break;
case "h6":
fontSize = 16;
break;
default:
fontSize = 16; // Default font size for other elements
}
// Retain existing font size and add the dynamic change
element.ref.current.style.fontSize = `${fontSize + intensit}px`;
break;
case "custom":
let t = otherWords.join(' ');
// Preserve existing styles and add the dynamic change
element.ref.current.style = element.ref.current.style.cssText + dynamicRepl(t, intensit);
break;
}
element.ref.current.style.translate = `${!effect.blending || isNaN(effect.blending) ? defaults.blending : effect.blending}ms`;
});
})
requestAnimationFrame(updateGradient);
}
};
}
export default useVisualizer;