我正在使用带有web音频api的麦克风输入,需要获取音量值。
现在我已经让麦克风正常工作了:http://updates.html5rocks.com/2012/09/Live-Web-Audio-Input-Enabled
此外,我还知道有一种方法可以控制音频文件的音量:http://www.html5rocks.com/en/tutorials/webaudio/intro/
// Create a gain node.
var gainNode = context.createGain();
// Connect the source to the gain node.
source.connect(gainNode);
// Connect the gain node to the destination.
gainNode.connect(context.destination);
// Reduce the volume.
gainNode.gain.value = 0.5;
但是如何将这两者结合起来并获得输入音量值呢?我只需要值,不需要操控它。
有人知道吗?
发布于 2018-08-15 21:09:50
虽然有点晚了,但我仍然希望能帮助你。
var audioContext = new (window.AudioContext || window.webkitAudioContext)()
var mediaStreamSource = null
var meter = null
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({audio: true}).then((stream) => {
mediaStreamSource = audioContext.createMediaStreamSource(stream)
meter = createAudioMeter(audioContext)
mediaStreamSource.connect(meter)
})
}
function createAudioMeter(audioContext, clipLevel, averaging, clipLag) {
const processor = audioContext.createScriptProcessor(512)
processor.onaudioprocess = volumeAudioProcess
processor.clipping = false
processor.lastClip = 0
processor.volume = 0
processor.clipLevel = clipLevel || 0.98
processor.averaging = averaging || 0.95
processor.clipLag = clipLag || 750
// this will have no effect, since we don't copy the input to the output,
// but works around a current Chrome bug.
processor.connect(audioContext.destination)
processor.checkClipping = function () {
if (!this.clipping) {
return false
}
if ((this.lastClip + this.clipLag) < window.performance.now()) {
this.clipping = false
}
return this.clipping
}
processor.shutdown = function () {
this.disconnect()
this.onaudioprocess = null
}
return processor
}
function volumeAudioProcess(event) {
const buf = event.inputBuffer.getChannelData(0)
const bufLength = buf.length
let sum = 0
let x
// Do a root-mean-square on the samples: sum up the squares...
for (var i = 0; i < bufLength; i++) {
x = buf[i]
if (Math.abs(x) >= this.clipLevel) {
this.clipping = true
this.lastClip = window.performance.now()
}
sum += x * x
}
// ... then take the square root of the sum.
const rms = Math.sqrt(sum / bufLength)
// Now smooth this out with the averaging factor applied
// to the previous sample - take the max here because we
// want "fast attack, slow release."
this.volume = Math.max(rms, this.volume * this.averaging)
document.getElementById('audio-value').innerHTML = this.volume
}
https://stackoverflow.com/questions/21247571
复制相似问题