我正在尝试使用Web Audio API找到音频时刻的强度。我在规范中找到的唯一与强度相关的东西是:
analyser.minDecibels
analyser.maxDecibels
有办法做到这一点吗?
答案 0 :(得分:3)
如果我理解正确,你需要一个在声音很大时为高的数字,在声音安静时为低。您可以使用“声压级”。
从Web Audio API获取此编号非常简单,您猜对了,我们将使用AnalyserNode来实现此目的。这是一个示例代码,向您展示如何执行此操作:
var ac = new AudioContext();
/* create the Web Audio graph, let's assume we have sound coming out of the
* node `source` */
var an = ac.createAnalyser();
source.connect(an);
/* Get an array that will hold our values */
var buffer = new Uint8Array(an.fftSize);
function f() {
/* note that getFloatTimeDomainData will be available in the near future,
* if needed. */
an.getByteTimeDomainData(buffer);
/* RMS stands for Root Mean Square, basically the root square of the
* average of the square of each value. */
var rms = 0;
for (var i = 0; i < buffer.length; i++) {
rms += buffer[i] * buffer[i];
}
rms /= buffer.length;
rms = Math.sqrt(rms);
/* rms now has the value we want. */
requestAnimationFrame(f);
}
requestAnimationFrame(f);
/* start our hypothetical source. */
source.start(0);
答案 1 :(得分:0)
四年后,我想感谢您的回答。 我只是做了一个快速的POC,并使其与以下代码一起使用。我希望它也可以对其他人有所帮助。
在此示例中,我从麦克风中获取实时音频,并将结果记录到控制台-在我的情况下,是在chrome开发工具下。
<html>
<head>
<title>Intensity test</title>
</head>
<body>
<script>
var ac = new AudioContext();
var an = ac.createAnalyser();
var source = "";
var buffer = new Uint8Array(an.fftSize);
var scriptProcessorNode = ac.createScriptProcessor(16384, 1, 1);
if (!navigator.getUserMedia)
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
if (navigator.getUserMedia){
navigator.getUserMedia({audio:true},
function(stream) {
source = ac.createMediaStreamSource(stream);
source.connect(an);
requestAnimationFrame(f);
},
function(e) {
alert('Error capturing audio.');
}
);
}
function f() {
an.getByteTimeDomainData(buffer);
var rms = 0;
for (var i = 0; i < buffer.length; i++) {
rms += buffer[i] * buffer[i];
}
rms /= buffer.length;
rms = Math.sqrt(rms);
requestAnimationFrame(f);
console.log(rms);
}
</script>
</body>
</html>