gpt4 book ai didi

javascript - 如何使用 navigator.mediaDevices.getUserMedia 降低麦克风输入音量?

转载 作者:行者123 更新时间:2023-12-03 02:19:59 28 4
gpt4 key购买 nike

我正在使用 navigator.mediaDevices.getUserMedia() 创建音频记录应用程序,它会记录我周围的每一个声音,即使是非常安静且距离我 10m 的声音。我不播放这个声音,我只是根据音量来想象它,所以我只需要相当大的声音或靠近麦克风的声音,因为干扰太多。

此外,如果我启用播放以听到麦克风输入并开始发出安静的噪音(例如敲击 table ),我无法在播放中听到此声音,但我在可视化工具中看到它,这正是我不想要的

这是我的代码:

const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
this.audioContext = new AudioContext();
this.sourceNode = this.audioContext.createMediaStreamSource(stream);
this.analyserNode = this.audioContext.createAnalyser();

this.sourceNode.connect(this.analyserNode);

const data = new Float32Array(this.analyserNode.fftSize);
this.analyserNode.getFloatTimeDomainData(data);

那么如何使用 Web Audio API 降低麦克风灵敏度或降低麦克风输入音量,或者转换来自分析器的数据?我读过有关 AudioContext.createGain()gain.volume 的内容,但它用于输出音频音量,而不是输入音量

最佳答案

I've read about AudioContext.createGain(), gain.volume, but it's used for output audio volume, not input one

不,它用于控制通过它的音频的音量。

您必须将音频上下文节点视为一条链,然后您可能会明白,您确实可以使用 GainNode 来控制它所连接的下一个节点的输入音量。

例如,如果我们声明类似的内容

gainNode.gain.volume = 0.5;
input.connect(gainNode);
gainNode.connect(analyserNode);
input.connect(audioContext.destination);

可以看作

Input [mic] ===>  GainNode  ===>  AnalyserNode
100% || 50% 50%
||
===> AudioContext Output
100%

因此,这里的增益节点确实降低了 AnalyserNode 的音量,但没有降低上下文输出的音量。

<小时/>

但这并不是您真正想要的。

事实上,AnalyserNode API 有 minDecibelsmaxDecibels属性将完全满足您的要求(过滤掉分贝范围之外的声音)。

但这些属性仅对频率数据 (getXXXFrequencyData) 有意义,因为波形不考虑音量。

但是,在决定是否应该绘制波形之前,仍然可以检查该频率数据是否在我们所需的范围内。

polyfill();

(async() => {

const ctx = new AudioContext();
const input = await loadFileAsBufferNode(ctx);
const analyser = ctx.createAnalyser();
analyser.minDecibels = -90;
analyser.maxDecibels = -10;
analyser.fftSize = 512;
input.connect(analyser);
const gainNode = ctx.createGain();
input.connect(gainNode);

const bufferLength = analyser.frequencyBinCount;
const freqArray = new Uint8Array(bufferLength);
const waveArray = new Uint8Array(bufferLength);

const canvasCtx = canvas.getContext('2d');
const WIDTH = canvas.width;
const HEIGHT = canvas.height;
canvasCtx.lineWidth = 2;

draw();
// taken from https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/maxDecibels#Example
function draw() {
requestAnimationFrame(draw);

canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
analyser.getByteFrequencyData(freqArray);

gainNode.gain.value = 1;
analyser.getByteTimeDomainData(waveArray);

var barWidth = (WIDTH / bufferLength) * 2.5;
var barHeight;
var x = 0;

for (var i = 0; i < bufferLength; i++) {
barHeight = freqArray[i];

canvasCtx.fillStyle = 'rgb(' + (barHeight + 100) + ',50,50)';
canvasCtx.fillRect(x, HEIGHT - barHeight / 2, barWidth, barHeight / 2);

x += barWidth + 1;
}
// here we check if the volume is in bounds
if (freqArray.some(isTooHigh) || !freqArray.some(hasValue)) {
canvasCtx.fillRect(0, HEIGHT / 2, WIDTH, 1);
gainNode.gain.value = 0;
return;
}

canvasCtx.beginPath();
var sliceWidth = WIDTH * 1.0 / bufferLength;
var x = 0;
for (var i = 0; i < bufferLength; i++) {
var v = waveArray[i] / 128.0;
var y = v * HEIGHT / 2;
if (i === 0) {
canvasCtx.moveTo(x, y);
} else {
canvasCtx.lineTo(x, y);
}
x += sliceWidth;
}

canvasCtx.lineTo(canvas.width, canvas.height / 2);
canvasCtx.stroke();

};

function isTooHigh(val) {
return val === 255;
}

function hasValue(val) {
return val;
}
// DOM
maxDB.oninput = e => {
const max = +maxDB.value;
if (+minDB.value >= max) minDB.value = analyser.minDecibels = max - 1;
analyser.maxDecibels = max;
}
minDB.oninput = e => {
const min = +minDB.value;
if (+maxDB.value <= min) maxDB.value = analyser.maxDecibels = min + 1;
analyser.minDecibels = min;
}
out.onchange = e => {
if (out.checked)
gainNode.connect(ctx.destination);
else
gainNode.disconnect(ctx.destination);
};

})();

function loadFileAsBufferNode(ctx, url = 'https://dl.dropboxusercontent.com/s/8c9m92u1euqnkaz/GershwinWhiteman-RhapsodyInBluePart1.mp3') {
return fetch(url)
.then(r => r.arrayBuffer())
.then(buf => ctx.decodeAudioData(buf))
.then(bufferNode => {
const source = ctx.createBufferSource();
source.buffer = bufferNode;
source.repeat = true;
source.start(0);
return source;
});
};

/* for Safari */
function polyfill() {
window.AudioContext = window.AudioContext || window.webkitAudioContext;
try {
const prom = new AudioContext().decodeAudioData(new ArrayBuffer()).catch(e => {});
} catch (e) {
const prev = AudioContext.prototype.decodeAudioData;
Object.defineProperty(AudioContext.prototype, 'decodeAudioData', {
get: () => asPromise
});

function asPromise(audioBuffer, done, failed) {
return new Promise((res, rej) => {
prev.apply(this, [audioBuffer, onsuccess, onerror]);
function onsuccess(buf) {
if (typeof done === 'function') done(buf);
res(buf);
}
function onerror(err) {
if (typeof failed === 'function') failed(err);
rej(err);
}
});
}
}
}
<label>min<input type="range" id="minDB" min="-100" max="-1" value="-90"></label>
<label>max<input type="range" id="maxDB" min="-99" max="0" value="-10"></label>
<label>output audio<input type="checkbox" id="out"></label>
<canvas id="canvas"></canvas>

关于javascript - 如何使用 navigator.mediaDevices.getUserMedia 降低麦克风输入音量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49204300/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com