我正在尝试在游戏中播放每次点击的声音效果,但声音有时会播放,而其他声音则不会!
我正在使用下一个代码:
<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>
有什么想法吗?
每当您使用音频标签时,请尝试在音频标签之后编写其脚本,如果您在该音频标签之前编写脚本,则在播放音频时会出现一些问题,
我建议在页面末尾编写脚本,这是编写脚本的标准方法。
http://jsfiddle.net/LyDWH/4/
<!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>
您可以使用以下代码播放音频
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");它会播放声音/效果.mp3也可以播放声音/效果.wav
尝试每次点击添加新的var声音和sound.play(),它将正常工作