2

我试图在每次点击时在游戏中播放音效,但有时声音会播放而其他声音不会!

我正在使用下一个代码:

<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>

有任何想法吗 ?

4

3 回答 3

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"); 它会播放声音/效果.mp3 或声音/效果.wav

于 2012-12-04T10:58:29.643 回答
0

每当您使用音频标签时,请尝试在音频标签之后编写其脚本,如果您在该音频标签之前编写脚本,则会在播放音频时出现问题,

我会推荐在页面末尾编写脚本,这是编写脚本的标准方式。

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>
​
于 2012-12-04T11:15:47.737 回答
-1

尝试每次点击添加一个新的 var 声音和 sound.play() 它会正常工作

于 2013-04-24T20:42:40.513 回答