You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
1.5 KiB

let timerInterval = null;
let startTime = null;
let secondsToSubtract = 0;
let micLevel = 0;
navigator.mediaDevices.getUserMedia({
audio: true
}).then((stream) => {
const audioContext = new AudioContext();
const analyser = audioContext.createAnalyser();
const microphone = audioContext.createMediaStreamSource(stream);
const scriptProcessor = audioContext.createScriptProcessor(2048, 1, 1);
analyser.smoothingTimeConstant = 0.8;
analyser.fftSize = 1024;
microphone.connect(analyser);
analyser.connect(scriptProcessor);
scriptProcessor.connect(audioContext.destination);
setInterval(() => {
const array = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(array);
const arraySum = array.reduce((a, value) => a + value, 0);
micLevel = arraySum / array.length;
document.querySelector('#mic').innerHTML = Math.round(micLevel);
}, 1000)
})
.catch((err) => {
console.error(err);
});
const updateTimerDisplay = ()=>{
if(micLevel < 15){
secondsToSubtract++;
}
const secondsSinceTimerStart = Math.floor((Date.now() - startTime)/1000);
document.querySelector('#seconds').innerHTML = secondsSinceTimerStart;
document.querySelector('#subtracted').innerHTML = secondsToSubtract;
document.querySelector('#total').innerHTML = secondsSinceTimerStart - secondsToSubtract;
}
document.querySelector('#start').addEventListener('click', ()=>{
startTime = Date.now();
timerInterval = window.setInterval(updateTimerDisplay,1000);
})
document.querySelector('#stop').addEventListener('click', ()=>{
window.clearInterval(timerInterval);
})