-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathusePreviewPublisher.js
78 lines (72 loc) · 2.67 KB
/
usePreviewPublisher.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
import React, { useState, useRef, useCallback, useContext } from 'react';
import { DEVICE_ACCESS_STATUS } from './../components/constants';
import useDevices from '../hooks/useDevices';
import * as VideoExpress from '@vonage/video-express';
export default function usePreviewPublisher() {
let previewPublisher = useRef();
let [logLevel, setLogLevel] = useState(0);
const [previewMediaCreated, setPreviewMediaCreated] = useState(false);
const [accessAllowed, setAccessAllowed] = useState(
DEVICE_ACCESS_STATUS.PENDING
);
const { deviceInfo, getDevices } = useDevices();
const calculateAudioLevel = React.useCallback((audioLevel) => {
let movingAvg = null;
if (movingAvg === null || movingAvg <= audioLevel) {
movingAvg = audioLevel;
} else {
movingAvg = 0.8 * movingAvg + 0.2 * audioLevel;
}
// 1.5 scaling to map the -30 - 0 dBm range to [0,1]
const currentLogLevel = Math.log(movingAvg) / Math.LN10 / 1.5 + 1;
setLogLevel(Math.min(Math.max(currentLogLevel, 0), 1) * 100);
}, []);
const createPreview = useCallback(
async (targetEl, publisherOptions) => {
try {
const publisherProperties = Object.assign({}, publisherOptions);
// console.log('[createPreview]', publisherProperties);
previewPublisher.current = new VideoExpress.PreviewPublisher(targetEl);
previewPublisher.current.on('audioLevelUpdated', (audioLevel) => {
calculateAudioLevel(audioLevel);
});
previewPublisher.current.on('accessAllowed', (audioLevel) => {
// console.log('[createPreview] - accessAllowed');
setAccessAllowed(DEVICE_ACCESS_STATUS.ACCEPTED);
getDevices();
});
previewPublisher.current.on('accessDenied', (audioLevel) => {
// console.log('[createPreview] - accessDenied');
setAccessAllowed(DEVICE_ACCESS_STATUS.REJECTED);
});
await previewPublisher.current.previewMedia({
targetElement: targetEl,
publisherProperties
});
setPreviewMediaCreated(true);
/* console.log(
'[Preview Created] - ',
previewPublisher.current.getVideoDevice()
); */
} catch (err) {
// console.log('[createPreview]', err);
}
},
[calculateAudioLevel, getDevices]
);
const destroyPreview = useCallback(() => {
if (previewPublisher && previewPublisher.current) {
previewPublisher.current.destroy();
console.log('[destroyPreview] - ', previewPublisher);
}
}, []);
return {
previewPublisher: previewPublisher.current,
createPreview,
destroyPreview,
logLevel,
previewMediaCreated,
accessAllowed,
deviceInfo
};
}