简单的麦克风音量计见https://codepen.io/www-0av-com/pen/jxzxEX
在 2018 年检查并正常工作,包括由 Chrome 浏览器中的安全更新引起的错误修复。
HTML
<h3>VU meter from mic input (getUserMedia API)</h3>
<button onclick="startr();" title="click start needed as security in browser increased and voice mic can only be started from a gesture on page">Start</button>
<canvas id="canvas" width="150" height="300" style='background:blue'></canvas>
<br>
CLICK START
<div align=left>See JS for attribution</div>
CSS
body {
color: #888;
background: #262626;
margin: 0;
padding: 40px;
text-align: center;
font-family: "helvetica Neue", Helvetica, Arial, sans-serif;
}
#canvas {
width: 150px;
height: 100px;
position: absolute;
top: 150px;
left: 45%;
text-align: center;
}
JS(需要 JQuery)
// Courtesy www/0AV.com, LGPL license or as set by forked host, Travis Holliday, https://codepen.io/travisholliday/pen/gyaJk
function startr(){
console.log ("starting...");
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia({
audio: true
},
function(stream) {
audioContext = new AudioContext();
analyser = audioContext.createAnalyser();
microphone = audioContext.createMediaStreamSource(stream);
javascriptNode = audioContext.createScriptProcessor(2048, 1, 1);
analyser.smoothingTimeConstant = 0.8;
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;
// console.log(Math.round(average - 40));
canvasContext.clearRect(0, 0, 150, 300);
canvasContext.fillStyle = '#BadA55';
canvasContext.fillRect(0, 300 - average, 150, 300);
canvasContext.fillStyle = '#262626';
canvasContext.font = "48px impact";
canvasContext.fillText(Math.round(average - 40), -2, 300);
// console.log (average);
} // end fn stream
},
function(err) {
console.log("The following error occured: " + err.name)
});
} else {
console.log("getUserMedia not supported");
}
}