效果
源码
<button id="open">打开麦克风</button>
<button id="close">关闭麦克风</button><input id="range" type="range" min="0" max="100" value="0" />
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;}