オーディオの振幅に基づいて svg 円要素の半径と色を変更する例を作成しました。
これは WebKit ブラウザーで機能しますが、それ以外は機能しません。私の知る限り、 Webkit ブラウザーはW3C Web Audio API Specの実装に近づいている唯一のブラウザーですが、 Mozilla Audio Data API Documentationは、Mozilla がその仕様を放棄し、Web Audio API も実装する予定であることを示しているようです。 . 私は幸いなことに、Internet Explorer の仕様の実装状況 (または実装の欠如) を知りません。
残念ながら、現時点では Flash 以外に優れたクロスブラウザー ソリューションは存在しないというのが答えですが、その道を進むと、モバイル デバイスにうんざりしてしまいます。
これは、完全に動作する JSBin の例です。
コードは次のとおりです。
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Drums</title>
</head>
<body>
<svg width="200" height="200">
<circle id="circle" r="10" cx="100" cy="100" />
</svg>
</body>
</html>
Javascript:
var context = new webkitAudioContext();
// Here's where most of the work happens
function processAudio(e) {
var buffer = e.inputBuffer.getChannelData(0);
var out = e.outputBuffer.getChannelData(0);
var amp = 0;
// Iterate through buffer to get the max amplitude for this frame
for (var i = 0; i < buffer.length; i++) {
var loud = Math.abs(buffer[i]);
if(loud > amp) {
amp = loud;
}
// write input samples to output unchanged
out[i] = buffer[i];
}
// set the svg circle's radius according to the audio's amplitude
circle.setAttribute('r',20 + (amp * 15));
// set the circle's color according to the audio's amplitude
var color = Math.round(amp * 255);
color = 'rgb(' + color + ',' + 0 + ',' + color + ')';
circle.setAttribute('fill',color);
}
window.addEventListener('load',function() {
var circle = document.getElementById('circle');
// Add an audio element
var audio = new Audio();
audio.src = 'http://www.mhat.com/phatdrumloops/audio/acm/mole_on_the_dole.wav';
audio.controls = true;
audio.preload = true;
document.body.appendChild(audio);
audio.addEventListener('canplaythrough',function() {
var node = context.createMediaElementSource(audio);
// create a node that will handle the animation, but won't alter the audio
// in any way
var processor = context.createJavaScriptNode(2048,1,1);
processor.onaudioprocess = processAudio;
// connect the audio element to the node responsible for the animation
node.connect(processor);
// connect the "animation" node to the output
processor.connect(context.destination);
// play the sound
audio.play();
});
});