-
Notifications
You must be signed in to change notification settings - Fork 15
/
microphone.js
69 lines (59 loc) · 1.59 KB
/
microphone.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
import sono from '../core/sono';
function microphone(connected, denied, error) {
navigator.getUserMedia =
navigator.mediaDevices.getUserMedia ||
navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
error = error || function(err) {
console.error(err);
};
const isSupported = !!navigator.getUserMedia;
const api = {};
let stream = null;
function onConnect(micStream) {
stream = micStream;
connected(stream);
}
function onError(e) {
if (denied && e.name === 'PermissionDeniedError' || e === 'PERMISSION_DENIED') {
denied();
} else {
error(e.message || e);
}
}
function connect() {
if (!isSupported) {
return api;
}
if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({
audio: true
}).then(onConnect).catch(onError);
} else {
navigator.getUserMedia({
audio: true
}, onConnect, onError);
}
return api;
}
function disconnect() {
if (stream.stop) {
stream.stop();
} else {
stream.getAudioTracks()[0].stop();
}
stream = null;
return api;
}
return Object.assign(api, {
connect,
disconnect,
isSupported,
get stream() {
return stream;
}
});
}
export default sono.register('microphone', microphone, sono.utils);