【问题标题】:webaudio microphone input volume is always 0网络音频麦克风输入音量始终为 0
【发布时间】:2021-09-03 16:56:17
【问题描述】:

我一直在尝试通过 webaudio api 从麦克风输入中获取实时音量。在阅读了一些文章后,我认为我有一些工作,但分析器和脚本处理器返回的音量似乎总是 0。

更新为将“麦克风”用作数据源

    // detect support for different browsers
    navigator.getUserMedia = (navigator.getUserMedia ||
                              navigator.webkitGetUserMedia ||
                              navigator.mozGetUserMedia ||
                              navigator.msGetUserMedia);
    
    var Mosquito = {
    
        setup : function(){
            // ask permission to grab the mic
            var stream = navigator.getUserMedia({ audio: true }, Mosquito.successCallback, Mosquito.errorCallback);
    },

    successCallback : function(localMediaStream){
        var audioContext = new AudioContext();

        // hook up the mic to the mediaStreamSource in audioContext
        var microphone = audioContext.createMediaStreamSource( localMediaStream );
        Mosquito.processAudio(microphone, audioContext);
    },

    processAudio : function(microphone, audioContext){
        // analyze a piece of the signal
        var analyser = audioContext.createAnalyser();
        analyser.smoothingTimeConstant = 0.3; // make it less jizzy
        analyser.fftSize = 512;

        // create a scriptProcessor in order to read out the analyser data
        var javascriptNode = audioContext.createScriptProcessor(2048, 1, 1);
        
        // connect all the things
        microphone.connect(analyser);
        analyser.connect(javascriptNode);
        javascriptNode.connect(audioContext.destination);


        javascriptNode.onaudioprocess = function(e){
            var array =  new Uint8Array(analyser.frequencyBinCount);
            analyser.getByteFrequencyData(array);
            console.log(array);
            var average = Mosquito.getAverageVolume(array);
            console.log(average);
            Mosquito.drawMeters(average);
        };
    },

    drawMeters : function(average){
        document.getElementById("meter").innerHTML = average;
    },

    getAverageVolume : function(array){
        var values = 0;
        var average;
 
        var length = array.length;
 
        // get all the frequency amplitudes
        for (var i = 0; i < length; i++) {
            values += array[i];
        }
 
        average = values / length;
        return average;
    },

    errorCallback : function(){
        console.log('nope');
    }
}
Mosquito.setup();

【问题讨论】:

    标签: web-audio-api


    【解决方案1】:

    为什么要创建缓冲源?您应该只连接媒体流源(当前未连接,这就是您没有获得任何数据的原因)。

    【讨论】:

    • 谢谢,我已将变量重命名为“麦克风”,并且确实看到我没有将其用作媒体流源。
    • 知道为什么分析仪会在几秒钟后停止,或者我应该为此打开一个新问题吗?
    • 我希望它与您的分析器和在 processAudio 函数中声明的 javascriptNode 相关,并且它们最终会被垃圾收集 - 尝试在全局范围内声明它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    • 2011-04-29
    • 2017-10-26
    相关资源
    最近更新 更多