要实现麦克风声音直接播放,并使用进度条显示音量,可以结合 Web Audio API 和 JavaScript 的一些 DOM 操作。我们可以使用 AnalyserNode 来获取音频数据,并计算音量,然后将其显示在进度条上。
- 以下是一个完整的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>麦克风声音直接播放及音量显示</title>
</head>
<body>
<h1>麦克风声音直接播放及音量显示</h1>
<div>
<button onclick="start()">开始</button>
<button onclick="stop()">停止</button>
</div>
<div>
<label for="volume">音量:</label>
<progress id="volume" value="0" max="1"></progress>
</div>
<script>
let audioContext;
let microphone;
let analyser;
let javascriptNode;
let audioStream;
let rafID;
function start() {
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
audioStream = stream;
audioContext = new (window.AudioContext || window.webkitAudioContext)();
analyser = audioContext.createAnalyser();
microphone = audioContext.createMediaStreamSource(stream);
javascriptNode = audioContext.createScriptProcessor(2048, 1, 1);
analyser.smoothingTimeConstant = 0.3;
analyser.fftSize = 1024;
microphone.connect(analyser);
analyser.connect(javascriptNode);
javascriptNode.connect(audioContext.destination);
microphone.connect(audioContext.destination); // 直接连接麦克风到扬声器
javascriptNode.onaudioprocess = () => {
let array = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteTimeDomainData(array);
let values = 0;
for (let i = 0; i < array.length; i++) {
let value = (array[i] - 128) / 128;
values += value * value;
}
let average = Math.sqrt(values / array.length);
let volumeProgressBar = document.getElementById('volume');
volumeProgressBar.value = average;
};
updateVolume();
})
.catch(err => {
console.error('麦克风权限获取失败:', err);
});
}
function updateVolume() {
rafID = requestAnimationFrame(updateVolume);
}
function stop() {
if (microphone) {
microphone.disconnect();
}
if (analyser) {
analyser.disconnect();
}
if (javascriptNode) {
javascriptNode.disconnect();
}
if (audioContext) {
audioContext.close();
}
if (audioStream) {
audioStream.getTracks().forEach(track => track.stop());
}
if (rafID) {
cancelAnimationFrame(rafID);
}
document.getElementById('volume').value = 0;
}
</script>
</body>
</html>
写代码以后都是AI的活了,码农没戏了.