HTML5 Audio Buffer getting stuck

蓝咒 提交于 2019-12-06 07:09:42

问题


I'm using the HTML5 webkitAudioContext to get the realtime levels of a user's microphone using this following code:

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

If you copy and paste this in to your console and click your fingers near your microphone (assuming you've enabled microphone input) you'll see it works for a few seconds, then suddenly stops. It doesn't report any errors. Can anybody explain why this is happening? Thanks

See http://labs.dinahmoe.com/dynamicmusicengine/ for an example where the levels are working correctly.


回答1:


I had the same problem but finally got the solution! The problem is the javascript node cicle. I suggest you to change the createJavaScriptNode() first:

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!



来源:https://stackoverflow.com/questions/15900103/html5-audio-buffer-getting-stuck

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!