前端基础(四十一):实时获取麦克风音量

let _mediaStream = null; let _scriptProcessor = null; document.querySelector('#open').onclick = () => { navigator.mediaDevices.getUserMedia({ audio: true }) .then(mediaStream => { _mediaStream = mediaStream; const audioContext = new AudioContext(); const mediaStreamSource = audioContext.createMediaStreamSource(_mediaStream); const analyser = audioContext.createAnalyser(); _scriptProcessor = audioContext.createScriptProcessor(2048, 1, 1); mediaStreamSource.connect(analyser); analyser.connect(_scriptProcessor); _scriptProcessor.connect(audioContext.destination); _scriptProcessor.onaudioprocess = audioProcessingEvent => { const uint8Array = new Uint8Array(analyser.frequencyBinCount); analyser.getByteFrequencyData(uint8Array); let volumeTotal = 0; uint8Array.forEach(d => volumeTotal += d); document.getElementById('range').value = volumeTotal / uint8Array.length; } }); } document.querySelector('#close').onclick = () => { const audioTracks = _mediaStream.getAudioTracks(); audioTracks.forEach(audioTrack => audioTrack.stop()); _scriptProcessor.disconnect(); document.querySelector('#range').value = 0; }
上一篇:【vba源码】导入excel批注信息


下一篇:用c++做游戏开发至少要掌握哪些知识?