。
這將工作在WebKit瀏覽器,但沒有別的。據我所知,Webkit瀏覽器是唯一實現了W3C Web Audio API Spec的瀏覽器,但Mozilla Audio Data API Documentation似乎表明Mozilla已經放棄了該規範,並且也將實現Web Audio API。我很幸福沒有意識到Internet Explorer的規範(或缺乏規範)的狀態。
不幸的是,現在的答案是,除了Flash之外,沒有其他跨瀏覽器的完美解決方案,但是如果你走這條路線,那麼你就會被困在移動設備上。
這是full, working JSBin example。
而這裏的代碼:
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();
});
});
你究竟是什麼意思?您發佈的視頻展示了一位在Flash中製作播放器的人,但您想要達到什麼目的? (一張圖片會很棒。) – corazza
我想動畫一個物體的振幅,即一個用聲音打開和關閉的喙。下面是Flash中如何工作的一個例子:http://beaubird.com/presentation.php –
這可能是新的HTML5功能,[看看這個](http://www.html5rocks.com/ en/tutorials/getusermedia/intro /) –