Microphone activity level of WebRTC MediaStream

前端 未结 3 382
不思量自难忘°
不思量自难忘° 2020-12-28 19:08

I would like some advice on how best to get the microphone activity level of an audio MediaStreamTrack javascript object in Chrome/Canary. The MediaStrea

3条回答
  •  青春惊慌失措
    2020-12-28 19:27

    What you are looking for is webkitAudioContext and its createMediaStreamSource method.

    Here's a code sample that draws green bar to act like a VU meter:

    navigator.webkitGetUserMedia({audio:true, video:true}, function(stream){
        audioContext = new webkitAudioContext();
        analyser = audioContext.createAnalyser();
        microphone = audioContext.createMediaStreamSource(stream);
        javascriptNode = audioContext.createJavaScriptNode(2048, 1, 1);
    
        analyser.smoothingTimeConstant = 0.3;
        analyser.fftSize = 1024;
    
        microphone.connect(analyser);
        analyser.connect(javascriptNode);
        javascriptNode.connect(audioContext.destination);
    
        canvasContext = $("#canvas")[0].getContext("2d");
    
        javascriptNode.onaudioprocess = function() {
            var array =  new Uint8Array(analyser.frequencyBinCount);
            analyser.getByteFrequencyData(array);
            var values = 0;
    
            var length = array.length;
            for (var i = 0; i < length; i++) {
                values += array[i];
            }
    
            var average = values / length;
            canvasContext.clearRect(0, 0, 60, 130);
            canvasContext.fillStyle = '#00ff00';
            canvasContext.fillRect(0,130-average,25,130);
        }
    
    }
    

    More details about AudioContext

提交回复
热议问题