navigator.getUserMedia() 音频录制 - 如何设置麦克风的音量输入水平?

6

现代浏览器中可以使用navigator.getUserMedia(...)调用来录制Javascript音频。

是否有方法可以调整/设置麦克风的输入音量水平?

这个设置并不总是最优的。有时,麦克风被设置为仅以非常低的输入音量记录。当然,用户可以在系统中手动调整输入音量级别,但我的大多数用户可能缺乏这样做的知识。因此,在通过“navigator.getUserMedia(...)”方式记录数据的JavaScript应用程序内动态调整麦克风音量最好?

是否有解决方案来影响麦克风的输入音量级别?

1个回答

9

Web Audio API 可以让你改变麦克风输入流的内容。

下面是一个例子,展示了如何将一个 MediaStream 转换为另一个 MediaStream,并且可以实时调整音量。如果你只想播放音频,则可以将 gainNode.connect(dest) 改为 gainNode.connect(ctx.destination) 并删除使用 dest 变量的另外两行代码。

if (!navigator.getUserMedia) {
    navigator.getUserMedia = navigator.webkitGetUserMedia ||
        navigator.mozGetUserMedia;
}
navigator.getUserMedia({
    audio: true
}, function(stream) {
    var ctx = new AudioContext();
    var source = ctx.createMediaStreamSource(stream);
    var dest = ctx.createMediaStreamDestination();
    var gainNode = ctx.createGain();

    source.connect(gainNode);
    gainNode.connect(dest);
    document.getElementById('volume').onchange = function() {
        gainNode.gain.value = this.value; // Any number between 0 and 1.
    };
    gainNode.gain.value = document.getElementById('volume').value;
    
    // Example: play the audio
    // Or if you use WebRTC, use peerConnection.addStream(dest.stream);
    new Audio(URL.createObjectURL(dest.stream)).play();

    // Store the source and destination in a global variable
    // to avoid losing the audio to garbage collection.
    window.leakMyAudioNodes = [source, dest];
}, function(e) {
    alert(e); // TODO: Handle error.
});

// For the demo only:
document.getElementById('volume').onchange = function() {
    alert('Please provide access to the microhone before using this.');
};
Volume: <input type=range id=volume min=0 max=1 value=1 step=0.01>

注意:由于getUserMedia在沙盒帧中似乎不起作用,因此通过Stack片段的实时演示在Chrome中无法工作。如果您使用Chrome,请尝试以下片段:https://robwu.nl/s/mediasource-change-volume.html

报告getUserMedia在沙箱问题中的问题,网址为https://code.google.com/p/chromium/issues/detail?id=488882。 - Rob W

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接