可以使用Audio API中的AudioBufferSourceNode节点和AudioContext对象来解决这个问题。
示例代码:
var context = new AudioContext(); var source = null;
function playSound(buffer) { source = context.createBufferSource(); source.buffer = buffer; source.connect(context.destination); source.start(0); }
function stopSound() { if (source) source.stop(0); }
var bufferLoader = new BufferLoader( context, [ 'sound1.wav', 'sound2.wav' ], finishedLoading );
bufferLoader.load();
function finishedLoading(bufferList) { document.getElementById("playButton").addEventListener("click", function() { playSound(bufferList[0]); }); document.getElementById("stopButton").addEventListener("click", function() { stopSound(); }); document.getElementById("playButton2").addEventListener("click", function() { playSound(bufferList[1]); }); }
在这个示例中,我们创建了一个AudioContext对象,并使用它来创建一个AudioBufferSourceNode对象。当按钮被点击时,我们调用playSound函数,将AudioBufferSourceNode节点连接到AudioDestinationNode节点,并启动播放。
当按钮再次被点击时,我们调用stopSound函数停止当前播放。使用这种方法,我们不需要担心第二个声音不能播放的问题。