-
Notifications
You must be signed in to change notification settings - Fork 162
/
Copy pathuseLocalAudioInputActivity.tsx
89 lines (69 loc) · 2.17 KB
/
useLocalAudioInputActivity.tsx
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { useEffect } from 'react';
import { useAudioVideo } from '../../providers/AudioVideoProvider';
import { useAudioInputs } from '../../providers/DevicesProvider';
import { RemovableAnalyserNode } from 'amazon-chime-sdk-js';
export const useLocalAudioInputActivity = (cb: (decimal: number) => void) => {
const audioVideo = useAudioVideo();
const { selectedDevice } = useAudioInputs();
useEffect(() => {
if (!audioVideo) {
return;
}
let analyserNode: RemovableAnalyserNode | null;
let restart = false;
let data: Uint8Array;
let frameIndex: number;
let isMounted = true;
let lastDecimal: number;
audioVideo.addDeviceChangeObserver({
audioInputsChanged: () => {
restart = true;
},
});
function initializePreview() {
if (!audioVideo || !isMounted) return;
analyserNode = audioVideo.createAnalyserNodeForAudioInput();
if (!analyserNode?.getByteTimeDomainData) {
return;
}
data = new Uint8Array(analyserNode.fftSize);
frameIndex = 0;
restart = false;
requestAnimationFrame(analyserNodeCallback);
}
function analyserNodeCallback() {
if (!analyserNode) {
return;
}
if (frameIndex === 0) {
analyserNode.getByteTimeDomainData(data);
const lowest = 0.01;
let max = lowest;
for (const f of data as any) {
max = Math.max(max, (f - 128) / 128);
}
const decimal = (Math.log(lowest) - Math.log(max)) / Math.log(lowest);
if (lastDecimal !== decimal) {
lastDecimal = decimal;
if (cb) {
cb(decimal);
}
}
}
frameIndex = (frameIndex + 1) % 2;
if (restart) {
setTimeout(initializePreview, 500);
} else if (isMounted) {
requestAnimationFrame(analyserNodeCallback);
}
}
initializePreview();
return () => {
isMounted = false;
analyserNode?.removeOriginalInputs();
};
}, [audioVideo, selectedDevice, cb]);
};
export default useLocalAudioInputActivity;