问题
Let me start by saying I am trying to play a mp3 file whenever the player collides with a wall, simple enough and done. But I wish to have another sound file play when the player hits another wall.
I have tried using both <audio>
tag in the html file, than playing it in Javascript:
var sound = document.getElementById("TheHtml5Tag");
Still the same issue, only one sound can be played, the next sound won't play untill the first one is finished. Even when using multiple <audio>
tags and multiple sounds.
Next I have tried using codes similar too:
sound = new Audio('Wall_Hit_01.mp3');
sound.addEventListener('ended', function() {
this.currentTime = 0;
}, false);
Than playing it with: sound.play();
But still the same issue: I can't play sound2.play();
or sound3.play();
before the first sound has finished.
Any answers/ suggestions are much appreciated. If there isn't a way to do this on every browser maybe some tips on how too stop all the sounds in order to play a new sound would be nice. Though I would much rather go with the original question.
回答1:
Howler.js provides a good library for firing off cross-browser sound sprites for games, should do the trick!
回答2:
I found a pretty neat solution that utilizes pure JavaScript.
In my HTML File, I put two audio elements and a play audio buttons in the same div.
<div id="audioplay">
<audio id='audio1' src="ex1.wav" type="audio/wav" preload="auto" autobuffer controls ></audio>
<audio id='audio2' src="ex2.wav" type="audio/wav" preload="auto" autobuffer controls></audio>
<button id='playaudio' onclick='playAudio()'>Play Audio</input>
In my JS file (you could use a script tag too), I put this code, which plays both of the files. Make sure that your audio src tags point to the right place!
function playAudio(){
var audio1 = document.getElementById('audio1');
var audio2 = document.getElementById('audio2');
audio1.play();
audio2.play();
}
Hope this helps!
来源:https://stackoverflow.com/questions/18015680/javascript-html5-play-multiple-audio-files-or-overlap-audio