Jac*_*ens 9 javascript audio html5
我正在尝试制作一款需要访问用户麦克风的小游戏.我需要能够检查麦克风是否已连接,然后如果是,请检查在游戏持续时间内通过麦克风传来的声音音量.我该怎么做?
Mor*_*sis 18
在我自己解决之后,稍微更详细的回答可能会帮助其他人看这里.
以下代码将根据麦克风音量注销大约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 */
});
Run Code Online (Sandbox Code Playgroud)
如果你有这个数字jquery来设置颜色块.我在下面提供了一个示例功能,但这是一个简单的部分.只需取消注释颜色pids功能.
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";
}
}
Run Code Online (Sandbox Code Playgroud)
为了确保这个答案尽可能详细,我还在下面附上了我的html和css,这样你就可以复制js html和css如果你希望得到一个正常运行的例子.
HTML:
<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>
Run Code Online (Sandbox Code Playgroud)
CSS:
.pids-wrapper{
width: 100%;
}
.pid{
width: calc(10% - 10px);
height: 10px;
display: inline-block;
margin: 5px;
}
Run Code Online (Sandbox Code Playgroud)
这是一个简单地使用setTimeout而不是不推荐使用的createScriptProcessor函数的答案:
(async () => {
let volumeCallback = null;
let volumeInterval = null;
const volumeVisualizer = document.getElementById('volume-visualizer');
const startButton = document.getElementById('start');
const stopButton = document.getElementById('stop');
// Initialize
try {
const audioStream = await navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: true
}
});
const audioContext = new AudioContext();
const audioSource = audioContext.createMediaStreamSource(audioStream);
const analyser = audioContext.createAnalyser();
analyser.fftSize = 512;
analyser.minDecibels = -127;
analyser.maxDecibels = 0;
analyser.smoothingTimeConstant = 0.4;
audioSource.connect(analyser);
const volumes = new Uint8Array(analyser.frequencyBinCount);
volumeCallback = () => {
analyser.getByteFrequencyData(volumes);
let volumeSum = 0;
for(const volume of volumes)
volumeSum += volume;
const averageVolume = volumeSum / volumes.length;
// Value range: 127 = analyser.maxDecibels - analyser.minDecibels;
volumeVisualizer.style.setProperty('--volume', (averageVolume * 100 / 127) + '%');
};
} catch(e) {
console.error('Failed to initialize volume visualizer, simulating instead...', e);
// Simulation
//TODO remove in production!
let lastVolume = 50;
volumeCallback = () => {
const volume = Math.min(Math.max(Math.random() * 100, 0.8 * lastVolume), 1.2 * lastVolume);
lastVolume = volume;
volumeVisualizer.style.setProperty('--volume', volume + '%');
};
}
// Use
startButton.addEventListener('click', () => {
// Updating every 100ms (should be same as CSS transition speed)
if(volumeCallback !== null && volumeInterval === null)
volumeInterval = setInterval(volumeCallback, 100);
});
stopButton.addEventListener('click', () => {
if(volumeInterval !== null) {
clearInterval(volumeInterval);
volumeInterval = null;
}
});
})();Run Code Online (Sandbox Code Playgroud)
div {
--volume: 0%;
position: relative;
width: 200px;
height: 20px;
margin: 50px;
background-color: #DDD;
}
div::before {
content: '';
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: var(--volume);
background-color: green;
transition: width 100ms linear;
}
button {
margin-left: 50px;
}
h3 {
margin: 20px;
font-family: sans-serif;
}Run Code Online (Sandbox Code Playgroud)
<h3><b>NOTE:</b> This is not accurate on stackoverflow, since microphone use is not permitted. It's a simulation instead.</h3>
<div id="volume-visualizer"></div>
<button id="start">Start</button>
<button id="stop">Stop</button>Run Code Online (Sandbox Code Playgroud)
这也意味着它可以根据需要轻松启动和停止。
这是检测可用的音频控件所需的片段(摘自:https : //developer.mozilla.org/en-US/docs/Web/API/Navigator/getUserMedia)
navigator.getUserMedia(constraints, successCallback, errorCallback);
Run Code Online (Sandbox Code Playgroud)
下面是一个使用 getUserMedia 函数的示例,该函数将使您能够访问麦克风。
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");
}
Run Code Online (Sandbox Code Playgroud)
这是一个演示您想要的“输入音量”的存储库。
https://github.com/cwilso/volume-meter/
简单的麦克风 Vu 表见 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;
}
Run Code Online (Sandbox Code Playgroud)
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");
}
}
Run Code Online (Sandbox Code Playgroud)