自学内容网 自学内容网

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

效果

在这里插入图片描述

源码

<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;

}

原文地址:https://blog.csdn.net/weixin_43526371/article/details/143865910

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!