3

我正在使用 HTML5 webkitAudioContext 使用以下代码获取用户麦克风的实时级别:

var liveSource;

function getLevel(){
    var context = new webkitAudioContext();  

    navigator.webkitGetUserMedia({audio: true}, function(stream) {

       liveSource = context.createMediaStreamSource(stream);
       liveSource.connect(context.destination);

       var levelChecker = context.createJavaScriptNode(4096, 1 ,1);
       liveSource.connect(levelChecker);

       levelChecker.connect(context.destination);

       levelChecker.onaudioprocess = function(e) {

            var buffer = e.inputBuffer.getChannelData(0);


        var maxVal = 0;
        // Iterate through buffer to check if any of the |values| exceeds 1.
        for (var i = 0; i < buffer.length; i++) {
            if (maxVal < buffer[i]) {
                maxVal = buffer[i];
            }
        }
        if(maxVal <= 0.01){
            console.log(0.0);
        } else if(maxVal > 1){
            console.log(1);
        } else if(maxVal > 0.2){
            console.log(0.2);
        } else if(maxVal > 0.1){
            console.log(0.1);
        } else if(maxVal > 0.05){
            console.log(0.05);
        } else if(maxVal > 0.025){
            console.log(0.025);
        } else if(maxVal > 0.01){
            console.log(0.01);
        }
};
});

 }

getLevel();

如果您将其复制并粘贴到您的控制台并在麦克风附近单击手指(假设您已启用麦克风输入),您会看到它工作了几秒钟,然后突然停止。它不报告任何错误。谁能解释为什么会这样?谢谢

有关级别正常工作的示例,请参见http://labs.dinahmoe.com/dynamicmusicengine/ 。

4

1 回答 1

4

我有同样的问题,但终于得到了解决方案!问题是javascript节点cicle。我建议您先更改 createJavaScriptNode() :

var levelChecker = context.createScriptProcessor(4096, 1 ,1);

The garbage collector has a problem with "levelChecker" variable and his onaudioprocess , so you have to bind the scriptprocessor or the onaudioProcess callback to the window. Here the HOLY SOLUTION:

 levelChecker.onaudioprocess = window.audioProcess = function(e) { ...

Just add window.audioProcess in that line and you will never deal with tat problem anymore.

Here you can find further info : http://lists.w3.org/Archives/Public/public-audio/2013JanMar/0304.html

Hope that works for you!

于 2013-11-21T15:45:58.867 回答