Search code examples
web-audio-api

webaudio microphone input volume is always 0


I've been trying to grab the real time volume from a microphone input via the webaudio api. After reading some articles I thought I had something working, but it seems like the volume returned from the analyser and scriptprocessor is always 0.

updated so that the "microphone" is used as a data source

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

Solution

  • Why are you creating a buffersource? You should just connect the mediastreamsource (which is currently unconnected, which is why you're not getting any data).