-
Notifications
You must be signed in to change notification settings - Fork 0
/
audio.js
99 lines (79 loc) · 2.73 KB
/
audio.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
var audioCtx;
var analyser;
var audioElement;
var sum1 = 0;
var sum2 = 0;
var sum3 = 0;
var sum4 = 0;
var sum5 = 0;
var sum6 = 0;
// const wrapper = () => {
// initializeAudio(audioElement);
// }
const initializeAudio = () => {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
analyser = audioCtx.createAnalyser();
handleAudioElement(audioElement);
try {
document.removeEventListener('click', initializeAudio);
} catch {
}
}
const handleAudioElement = (audioElement) => {
audioElement.src = 'audio/' + currentIdx + '.mp3';
// Connect the audio element to the analyser node
var source = audioCtx.createMediaElementSource(audioElement);
source.connect(analyser);
analyser.connect(audioCtx.destination);
// Set the FFT size (frequency bin count)
analyser.fftSize = 2048;
var bufferLength = analyser.frequencyBinCount;
var dataArray = new Uint8Array(bufferLength);
// Function to update frequency data
var x = 0;
function updateFrequencyData() {
if (x % 100 == 0) {
// console.log(JSON.stringify(dataArray));
}
x++;
analyser.getByteFrequencyData(dataArray);
sum1 = calculateSum(dataArray.slice(0,125));
sum2 = calculateSum(dataArray.slice(125,250));
sum3 = calculateSum(dataArray.slice(250,375));
sum4 = calculateSum(dataArray.slice(375,500));
sum5 = calculateSum(dataArray.slice(500,625));
sum6 = calculateSum(dataArray.slice(625,1024));
// Process the frequency data
// Here, you can access the frequency data in the dataArray
// Each index in the array represents a specific frequency bin
requestAnimationFrame(updateFrequencyData);
}
// Start updating frequency data
updateFrequencyData();
}
// Create a mutation observer
var observer = new MutationObserver(function(mutationsList) {
// Check each mutation for added nodes
mutationsList.forEach(function(mutation) {
var addedNodes = mutation.addedNodes;
// Check if any of the added nodes are <audio> elements
for (var i = 0; i < addedNodes.length; i++) {
if (addedNodes[i].nodeName === 'AUDIO') {
audioElement = addedNodes[i];
document.addEventListener("click", initializeAudio);
// Disconnect the observer since we no longer need it
// observer.disconnect();
return;
}
}
});
});
// Start observing changes to the document
observer.observe(document, { childList: true, subtree: true });
function calculateSum(arr) {
var s = 0;
for (var i = 0; i < arr.length; i++) {
s += arr[i];
}
return s;
}