使用WebAudio API计算现场麦克风音频频率的简单代码

Simple code to calculate frequency of Live Mic Audio using WebAudio API

本文关键字:频率 简单 代码 音频 麦克风 WebAudio API 计算 现场 使用      更新时间:2023-09-26

我有一个网站,需要在其中显示实时麦克风音频的频率。我有一个这个代码,但它非常难理解(它使用傅立叶变换和所有)。在一些研究中,我了解了返回音频频率的getByteFrequencyData()。以前有人在网络音频API中使用过现场麦克风音频吗?

我写了一个简单的代码,你可以在网页中显示频率:

const audioCtx = new AudioContext();
const analyser = audioCtx.createAnalyser();
const source = audioCtx.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(audioCtx.destination);
analyser.fftSize = 32;
let frequencyData = new Uint8Array(analyser.frequencyBinCount);
function renderFrame() {
    analyser.getByteFrequencyData(frequencyData);
    P10.style.height = ((frequencyData[0] * 100) / 256) + "%";
    P20.style.height = ((frequencyData[1] * 100) / 256) + "%";
    P30.style.height = ((frequencyData[2] * 100) / 256) + "%";
    P40.style.height = ((frequencyData[3] * 100) / 256) + "%";
    P50.style.height = ((frequencyData[4] * 100) / 256) + "%";
    P60.style.height = ((frequencyData[5] * 100) / 256) + "%";
    P70.style.height = ((frequencyData[6] * 100) / 256) + "%";
    P80.style.height = ((frequencyData[7] * 100) / 256) + "%";
    P90.style.height = ((frequencyData[8] * 100) / 256) + "%";
    console.log(frequencyData)
    requestAnimationFrame(renderFrame);
}
audio.pause();
audio.play();
renderFrame();
#bar {
    position: fixed;
    top: 20%;
    left: 40%;
    width: 40%;
    height: 40%;
    -webkit-transition: 0.1s ease all;
}
.p {
    background-color: blue;
    height: 100%;
    width: 10%;
    float: left;
}
<audio id="audio" src="2.mp3"></audio>
<div id="bar">
    <div id="P10" class="p"></div>
    <div id="P20" class="p"></div>
    <div id="P30" class="p"></div>
    <div id="P40" class="p"></div>
    <div id="P50" class="p"></div>
    <div id="P60" class="p"></div>
    <div id="P70" class="p"></div>
    <div id="P80" class="p"></div>
    <div id="P90" class="p"></div>
</div>

祝你好运。

"显示频率"可能意味着很多事情。事实上,我的PitchDetect演示不使用傅立叶变换,而是使用自相关。但这只会给你一次高精度的投球。如果你的信号同时有多个音符,那就很难了。

如果你想查看现场麦克风输入的频率分析明细,请查看http://webaudiodemos.appspot.com/AudioRecorder/index.html(代码位于https://github.com/cwilso/AudioRecorder)。它使用RealtimeAnalyser中的内置FFT来显示实时音频信号的频谱图。