Javascript 网络音频有效值未读取流

Javascript web audio rms not reading stream

我开发了一个网页,可以监听麦克风,计算均方根(平均响度)并改变网页上text areas的颜色。

我找到了 audio-rms package,但该示例使用了振荡器,我不确定如何用麦克风流替换它。

然后我在 HTML5 Rocks about capturing audio 上找到了一篇文章,我使用了一些代码来实时捕获音频。

我已经有一些代码可以从流中计算 rms,但问题是麦克风从不发送任何音频。通过使用控制台日志,我发现代码在第 8 行运行,但在第 11 行不起作用,这恰好是在调用 navigator.mediaDevices.getUserMedia

我使用的代码如下,您可以在GitHub上查看文件:

+function () {
    var errorCallback = function (e) {
        console.log('Permission Rejected!', e);
    };
    var ctx = new AudioContext()

    if (navigator.mediaDevices.getUserMedia) {
        //works here
        navigator.mediaDevices.getUserMedia({audio: true}, function (stream) 
        {
            //Doesn't work here.
            // 2048 sample buffer, 1 channel in, 1 channel out  
            var processor = ctx.createScriptProcessor(2048, 1, 1)
            var source
            console.log("processor")
            source = ctx.createMediaElementSource(stream)
            console.log("media element")
            source.connect(processor)
            source.connect(ctx.destination)
            processor.connect(ctx.destination)
            stream.play()
            console.log("stream play")

            // loop through PCM data and calculate average
            // volume for a given 2048 sample buffer
            processor.onaudioprocess = function (evt) {
                var input = evt.inputBuffer.getChannelData(0)
                  , len = input.length
                  , total = i = 0
                  , rms
                while (i < len) total += Math.abs(input[i++])
                rms = Math.sqrt(total / len)

                console.log(rmsLevel)

                if (rmsLevel > 65) { document.getElementById("TL").style.backgroundColor = "rgb(255, 0, 0)"; }
                else if (rmsLevel > 60 && rmsLevel <= 65) { document.getElementById("L").style.backgroundColor = "rgb(255, 140, 0)"; }
                ...
            }
        }, errorCallback);
    } else {
        alert("Error. :(")
    }
}()


function resetColours() {
    document.getElementById("TL").style.backgroundColor = "rgb(110, 110, 110)";
    document.getElementById("L").style.backgroundColor = "rgb(110, 110, 110)";
    ...
}

您对 navigator.MediaDevices.getUserMedia 的用法不正确 - 您使用 navigator.getUserMedia 回调的旧样式编写它,而不是 navigator.MediaDevices.gUM 基于 Promise 的方式。看看https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia.

而不是

navigator.mediaDevices.getUserMedia({audio: true}, function (stream) {
    ...
}, errorcallback );

你应该说

navigator.mediaDevices.getUserMedia({audio: true}).then( function (stream) {
    ...
}).catch(function(err) {
  /* handle the error */
});