我有一个简单的4秒音频剪辑,每秒单击一次。我有一个带有4个圆圈的SVG图片。我希望能够无限循环音频,并使圆圈每秒显示/隐藏一次并与音频同步。所以...
0 seconds, show just the red circle
1 second, show just the green circle
2 seconds, show just the yellow circle
3 seconds, show just the blue circle (audio loops to the beggining, time is reset to 0)
0 seconds, show just the red circle
etc...
一切正常,除了我不知道如何捕获循环的时间。 (请参见下面的javascript,其中显示“某些事件listener()”)。有什么想法吗?
<button id='go'>Go</button>
<button id='stop'>Stop</button>
<br/><br/>
<svg width='500' height='100'>
<rect width="250" height="100" style="fill:Tan;stroke-width:3;stroke:rgb(0,0,0)" />
<g id='circle1'><circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /></g>
<g id='circle2'><circle cx="100" cy="50" r="40" stroke="black" stroke-width="3" fill="green" /></g>
<g id='circle3'><circle cx="150" cy="50" r="40" stroke="black" stroke-width="3" fill="yellow" /></g>
<g id='circle4'><circle cx="200" cy="50" r="40" stroke="black" stroke-width="3" fill="blue" /></g>
</svg>
var actx = new (AudioContext || webkitAudioContext)(),
src = "https://smantei.s3-us-west-2.amazonaws.com/Click.wav",
audioData, srcNode;
fetch(src, {mode: "cors"}).then(function(resp) {return resp.arrayBuffer()}).then(decode);
function decode(buffer) {
actx.decodeAudioData(buffer, playLoop);
}
function playLoop(abuffer) {
if (!audioData) audioData = abuffer;
srcNode = actx.createBufferSource();
srcNode.buffer = abuffer;
srcNode.connect(actx.destination);
srcNode.loop = true;
srcNode.start();
}
document.querySelector("#go").onclick = function() {
playLoop(audioData);
};
document.querySelector("#stop").onclick = function() {
srcNode.stop();
};
/*
some event listener() {
if (time >= 0 && time < 1.0) {
document.querySelector("#circle1").style.display = 'block';
document.querySelector("#circle2").style.display = 'none';
document.querySelector("#circle3").style.display = 'none';
document.querySelector("#circle4").style.display = 'none';
}
if (time >= 1.0 && time < 2.0) {
document.querySelector("#circle1").style.display = 'none';
document.querySelector("#circle2").style.display = 'block';
document.querySelector("#circle3").style.display = 'none';
document.querySelector("#circle4").style.display = 'none';
}
if (time >= 2.0 && time < 3.0) {
document.querySelector("#circle1").style.display = 'none';
document.querySelector("#circle2").style.display = 'none';
document.querySelector("#circle3").style.display = 'block';
document.querySelector("#circle4").style.display = 'none';
}
if (time >= 3.0 && time < 4.0) {
document.querySelector("#circle1").style.display = 'none';
document.querySelector("#circle2").style.display = 'none';
document.querySelector("#circle3").style.display = 'none';
document.querySelector("#circle4").style.display = 'block';
}
}
*/
由于正在循环播放音频剪辑,因此没有可用的事件。但是,如果您使用了4个单独的1秒剪辑,则可以安排每个剪辑开始播放。然后,您将从每个剪辑中获得一个预期事件,该事件可用于驱动SVG动画。
但是,这意味着您必须通过每4秒不断安排新剪辑来进行自己的音频循环。确保在当前回合结束之前安排下一回合的安排,并且不要使用onended事件安排下一个剪辑。随着时间的流逝,它会慢慢漂移,但是对于您的应用程序来说可能是可以接受的。