forked from Shubham56-droid/Web-Components-Projects
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmicrophone.js
More file actions
35 lines (33 loc) · 1.26 KB
/
microphone.js
File metadata and controls
35 lines (33 loc) · 1.26 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
class Microphone {
constructor(){
this.initialized = false;
navigator.mediaDevices.getUserMedia({audio:true})
.then(function(stream){
this.audioContext = new AudioContext();
this.microphone = this.audioContext.createMediaStreamSource(stream);
this.analyser = this.audioContext.createAnalyser();
this.analyser.fftSize = 512;
const bufferLength = this.analyser.frequencyBinCount;
this.dataArray = new Uint8Array(bufferLength);
this.microphone.connect(this.analyser);
this.initialized = true;
}.bind(this)).catch(function(err){
alert(err);
});
}
getSamples(){
this.analyser.getByteTimeDomainData(this.dataArray);
let normSamples = [...this.dataArray].map(e => e/128 - 1);
return normSamples;
}
getVolume(){
this.analyser.getByteTimeDomainData(this.dataArray);
let normSamples = [...this.dataArray].map(e => e/128 - 1);
let sum = 0;
for(let i = 0; i < normSamples.length; i++){
sum += normSamples[i] * normSamples[i];
}
let volume = Math.sqrt( sum / normSamples.length);
return volume;
}
}