在Javascript中检查麦克风音量
我正在尝试制作一个需要访问用户麦克风的小游戏。我需要能够检查麦克风是否已连接,如果已连接,请检查整个游戏期间通过麦克风发出的音量。我该怎么做呢?以下是检测音频控件是否可用所需的代码片段(从:) 下面是一个使用getUserMedia函数的示例,该函数将使您能够访问麦克风在Javascript中检查麦克风音量,javascript,html,audio,Javascript,Html,Audio,我正在尝试制作一个需要访问用户麦克风的小游戏。我需要能够检查麦克风是否已连接,如果已连接,请检查整个游戏期间通过麦克风发出的音量。我该怎么做呢?以下是检测音频控件是否可用所需的代码片段(从:) 下面是一个使用getUserMedia函数的示例,该函数将使您能够访问麦克风 navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia({ audio: true, video: { width: 1280, height: 720 } },
function(stream) {
console.log("Accessed the Microphone");
},
function(err) {
console.log("The following error occured: " + err.name);
}
);
} else {
console.log("getUserMedia not supported");
}
下面是一个存储库,它演示了您想要的“输入量”
简易话筒Vu表见 2018年检查并工作,包括Chrome浏览器安全更新导致的错误修复 HTML 麦克风输入的VU计(getUserMedia API) 开始
单击开始 属性见JS CSS JS(需要JQuery)
//由www/0AV.com提供,LGPL许可证或由forked主机Travis Holliday设置,https://codepen.io/travisholliday/pen/gyaJk
函数startr(){
console.log(“启动…”);
navigator.getUserMedia=navigator.getUserMedia||
navigator.webkitGetUserMedia||
navigator.mozGetUserMedia;
if(navigator.getUserMedia){
navigator.getUserMedia({
音频:正确
},
功能(流){
audioContext=新的audioContext();
Analyzer=audioContext.createAnalyzer();
麦克风=audioContext.createMediaStreamSource(流);
javascriptNode=audioContext.createScriptProcessor(2048,1,1);
分析仪.平滑时间常数=0.8;
Analyzer.fftSize=1024;
麦克风。连接(分析仪);
connect(javascriptNode);
连接(audioContext.destination);
canvasContext=$(“#canvas”)[0].getContext(“2d”);
javascriptNode.onaudioprocess=function(){
var阵列=新UINT8阵列(分析仪频率BINCOUNT);
分析仪。GetByTefFrequencyData(阵列);
var值=0;
var length=array.length;
对于(变量i=0;i
一个稍微详细一点的答案,在我自己解决之后,我觉得可能会帮助其他人在这里寻找答案
以下代码将根据麦克风音量注销大约0到100的数字
navigator.mediaDevices.getUserMedia({ audio: true, video: true })
.then(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);
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));
// colorPids(average);
}
})
.catch(function(err) {
/* handle the error */
});
毕竟你最终会得到这样的结果。
这里是一个简单的答案,使用
setTimeout
而不是不推荐的createScriptProcessor
函数:
(异步()=>{
设volumeCallback=null;
让volumeInterval=null;
const volumeVisualizer=document.getElementById('volume-visualizer');
const startButton=document.getElementById('start');
const stopButton=document.getElementById('stop');
//初始化
试一试{
const audioStream=等待navigator.mediaDevices.getUserMedia({
音频:{
回声消除:对
}
});
const audioContext=新的audioContext();
const audioSource=audioContext.createMediaStreamSource(audioStream);
const analyzer=audioContext.createanalyzer();
Analyzer.fftSize=512;
分析仪。minDecibels=-127;
分析仪最大分贝=0;
分析仪.平滑时间常数=0.4;
音频源。连接(分析仪);
常量体积=新UINT8阵列(分析仪频率BINCOUNT);
volumeCallback=()=>{
分析仪。GetByTefFrequencyData(体积);
设体积um=0;
for(const volume of volumes)
体积um+=体积;
const averageVolume=volumeSum/volumes.length;
//值范围:127=分析仪最大分贝-分析仪最小分贝;
volumeVisualizer.style.setProperty('--volume',(averageVolume*100/127)+'%');
};
}捕获(e){
console.error('未能初始化卷可视化工具,而是模拟…',e);
//模拟
//生产中的TODO删除!
设lastVolume=50;
volumeCallback=()=>{
const volume=Math.min(Math.max(Math.random()*100,0.8*lastVolume),1.2*lastVolume);
lastVolume=体积;
volumeVisualizer.style.setProperty('--volume',volume+'%');
};
}
//使用
startButton.addEventListener('单击',()=>{
//每100ms更新一次(应与CSS转换速度相同)
if(volumeCallback!==null&&volumeInterval==null)
volumeInterval=设置间隔(volumeCallback,100);
});
stopButton.addEventListener('单击',()=>{
如果(volumeInterval!==null){
清除间隔(体积间隔);
volumeInterval=null;
}
});
})();代码>
div{
--体积:0%;
位置:相对位置;
宽度:200px;
高度:20px;
利润率:50像素;
背景色:#DDD;
}
div::之前{
内容:'';
位置:绝对位置;
排名:0;
底部:0;
左:0;
宽度:var(--体积);
背景颜色:绿色;
过渡:宽度100ms线性;
}
钮扣{
左边距:50像素;
}
h3{
利润率:20px;
字体系列:无衬线;
}
注意:这在stackoverflow上不准确,因为不允许使用麦克风。这是一个模拟。
开始
住手
非常感谢。这真的很有帮助!OP说检查麦克风发出的声音的音量
。我看不出这个答案有什么帮助。他最初的问题是看话筒是如何连接的,然后如果连接了检查声音的音量
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;
}
// 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");
}
}
navigator.mediaDevices.getUserMedia({ audio: true, video: true })
.then(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);
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));
// colorPids(average);
}
})
.catch(function(err) {
/* handle the error */
});
function colorPids(vol) {
let all_pids = $('.pid');
let amout_of_pids = Math.round(vol/10);
let elem_range = all_pids.slice(0, amout_of_pids)
for (var i = 0; i < all_pids.length; i++) {
all_pids[i].style.backgroundColor="#e6e7e8";
}
for (var i = 0; i < elem_range.length; i++) {
// console.log(elem_range[i]);
elem_range[i].style.backgroundColor="#69ce2b";
}
}
<div class="pids-wrapper">
<div class="pid"></div>
<div class="pid"></div>
<div class="pid"></div>
<div class="pid"></div>
<div class="pid"></div>
<div class="pid"></div>
<div class="pid"></div>
<div class="pid"></div>
<div class="pid"></div>
<div class="pid"></div>
</div>
.pids-wrapper{
width: 100%;
}
.pid{
width: calc(10% - 10px);
height: 10px;
display: inline-block;
margin: 5px;
}