我试图在每次击中的游戏中发挥声音效果,但声音有时会播放而其他声音不会播放!!
我正在使用下一个代码:
<script>
var hitSound = new Audio();
function playEffectSound()
{
hitSound = document.getElementById('effects');
hitSound.loop = false;
hitSound.currentTime = 0;
hitSound.play();
}
</script>
<audio id="effects" hidden>
<source src="sound/mp3/effect.mp3" type="audio/mpeg">
<source src="sound/wav/effect.wav" type="audio/wav">
</audio>
任何想法?
答案 0 :(得分:0)
您可以使用以下代码播放音频
function playEffectSound(sound) {
//Does the sound already exist?
if (document.getElementById(sound) != null) {
document.getElementById(sound).play();
return;
}
//Create elements
var audioElement = document.createElement("audio");
var sourceElement = document.createElement("source");
sourceElement.src = sound + ".mp3";
sourceElement.type = "audio/mpeg";
var sourceElementWave = document.createElement("source");
sourceElementWave.src = sound + ".wav";
sourceElementWave.type = "audio/wav";
//Add sources to audio
document.body.appendChild(sourceElementWave);
document.body.appendChild(audioElement);
audioElement.setAttribute("id", sound);
audioElement.appendChild(sourceElement);
audioElement.loop = false;
audioElement.currentTime = 0;
audioElement.play();
}
您可以像这样使用它:playEffectSound(“sounds / effect”);它将播放sounds / effect.mp3或sounds / effect.wav
答案 1 :(得分:0)
每当您使用音频标签时,请尝试在音频标签之后编写其脚本,如果您在该音频标签之前编写脚本,则会在播放音频时出现问题,
我建议在页面末尾写下编写脚本,这是编写脚本的标准方法。
<!DOCTYPE html>
<html>
<body>
<audio id="effects" hidden >
<source src="http://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
</audio>
<div onclick= "playEffectSound();">Horse Click Me..!</div>
</body>
<script>
var hitSound = new Audio();
function playEffectSound()
{
hitSound = document.getElementById('effects');
hitSound.currentTime = 0;
hitSound.play();
}
</script>
</html>
答案 2 :(得分:-1)
尝试每次点击添加一个新的var声音和sound.play(),它将正常工作