-
Notifications
You must be signed in to change notification settings - Fork 22
/
sound.js
92 lines (75 loc) · 2.32 KB
/
sound.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
// Sound recognition
// TODO: determine period of relative silence
var soundSource = (function(global) {
var id = 'source-sound',
title = 'Sound',
enabled = 'mediaDevices' in navigator;
function start() {
/*
if (navigator.mediaDevices.enumerateDevices) {
navigator.mediaDevices.enumerateDevices().then(a =>
a.forEach(d =>
console.log(d)
)
);
}
*/
if ('mediaDevices' in navigator) {
navigator.mediaDevices.getUserMedia({ audio: true })
.then(onMediaStreamHandler)
.catch(function(error) {
console.log('getUserMedia error: ', err);
});
}
}
function onMediaStreamHandler(stream) {
stream.onactive = function(e) { console.log('stream active', e) };
stream.onaddtrack = function(e) { console.log('stream track added', e) };
stream.onended = function(e) { console.log('stream ended', e) };
stream.oninactive = function(e) { console.log('stream inactive', e) };
stream.onremovetrack = function(e) { console.log('stream track removed', e) };
var audioCtx = new AudioContext();
var analyser = audioCtx.createAnalyser();
analyser.minDecibels = -90;
analyser.maxDecibels = -10;
analyser.smoothingTimeConstant = 0.85;
var source = audioCtx.createMediaStreamSource(stream);
global.source = source; // hack for bug 934512
source.connect(analyser);
var gainNode = audioCtx.createGain();
gainNode.connect(audioCtx.destination);
var bufferLength = analyser.fftSize;
var dataArray = new Uint8Array(analyser.frequencyBinCount);
var rAFHandle = null,
avgVolume = 0,
lastVolume = 0;
(function draw() {
rAFHandle = requestAnimationFrame(draw);
analyser.getByteFrequencyData(dataArray);
avgVolume = getAverageVolume(dataArray);
})();
setInterval(function() {
if (avgVolume) {
publish(id, {
id: 'avgVolume',
value: avgVolume,
type: 'stream',
label: 'Average Volume'
});
}
lastVolume = avgVolume
}, 1000);
function getAverageVolume(data) {
return data.reduce(function(sum, value){
return sum + value;
}, 0) / data.length;
}
}
// public
return {
id: id,
title: title,
enabled: enabled,
start: start
};
})(this);