マイクを聞いて、平均平方根(平均音量)を計算し、ウェブページのtext areas
の色を変更するウェブページを作成しました。Javascript web audio rmsがストリームを読み込まない
私はaudio-rms
packageを見つけましたが、この例ではオシレータを使用していますが、マイクストリームで置き換える方法がわかりません。
私はHTML5 Rocks about capturing audioの記事を見つけ、リアルタイムで使用するためにオーディオをキャプチャするためにいくつかのコードを使用しました。
ストリームからrms
を計算するはずのコードが既にありますが、マイクがオーディオを送信しないという問題があります。コンソールログを使用することで、コードは8行目まで機能することがわかりましたが、11行目では動作しません。navigator.mediaDevices.getUserMedia
私が使用しているコードは以下のとおりです。 GitHub上:
+function() {
var errorCallback = function (e) {
console.log('Permission Rejected!', e);
};
var ctx = new AudioContext()
if (navigator.mediaDevices.getUserMedia) {
//works here
navigator.mediaDevices.getUserMedia({audio: true}, function (stream)
{
//Doesn't work here.
// 2048 sample buffer, 1 channel in, 1 channel out
var processor = ctx.createScriptProcessor(2048, 1, 1)
var source
console.log("processor")
source = ctx.createMediaElementSource(stream)
console.log("media element")
source.connect(processor)
source.connect(ctx.destination)
processor.connect(ctx.destination)
stream.play()
console.log("stream play")
// loop through PCM data and calculate average
// volume for a given 2048 sample buffer
processor.onaudioprocess = function (evt) {
var input = evt.inputBuffer.getChannelData(0)
, len = input.length
, total = i = 0
, rms
while (i < len) total += Math.abs(input[i++])
rms = Math.sqrt(total/len)
console.log(rmsLevel)
if (rmsLevel > 65) { document.getElementById("TL").style.backgroundColor = "rgb(255, 0, 0)"; }
else if (rmsLevel > 60 && rmsLevel <= 65) { document.getElementById("L").style.backgroundColor = "rgb(255, 140, 0)"; }
...
}
}, errorCallback);
} else {
alert("Error. :(")
}
}()
function resetColours() {
document.getElementById("TL").style.backgroundColor = "rgb(110, 110, 110)";
document.getElementById("L").style.backgroundColor = "rgb(110, 110, 110)";
...
}