-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStreamContext.js
More file actions
55 lines (47 loc) · 1.33 KB
/
Copy pathStreamContext.js
File metadata and controls
55 lines (47 loc) · 1.33 KB
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
import { useEffect, createContext, useState } from 'react'
const StreamContext = createContext({})
const StreamContextProvider = ({ children }) => {
const [micAudioStream, setMicAudioStream] = useState(null)
const [micAudioStreamError, setMicAudioStreamError] = useState()
const [micAccess, setMicAccess] = useState(false)
const [micMuted, setMicMuted] = useState(false)
async function startMicStream() {
if (micAudioStream) return micAudioStream
try {
const stream = await navigator.mediaDevices.getUserMedia({
audio: true
})
setMicAudioStream(stream)
return stream
} catch(err) {
setMicAudioStreamError(err)
return err
}
}
function checkMicPermission() {
navigator.permissions.query(
{ name: 'microphone' }
).then(function(permissionStatus){
setMicAccess(permissionStatus.state)
})
}
function muteToggle() {
if (!micAudioStream) return
const stream = micAudioStream.getAudioTracks()[0];
setMicMuted(stream.enabled);
stream.enabled = !stream.enabled;
}
return (
<StreamContext.Provider value={{
checkMicPermission,
startMicStream,
micAudioStream,
micAccess,
muteToggle,
micMuted,
}}>
{children}
</StreamContext.Provider>
)
}
export { StreamContext, StreamContextProvider }