音频未在JS中播放

时间:2018-12-15 12:03:36

标签: javascript html audio

我一直遇到音频无法播放的问题。我试图播放随机声音,但是单击图像(具有onclick="playRandomSound()")时没有任何反应。这是我的代码。

var sound1 = new Audio("InDeed.wav");
var sound2 = new Audio("Indeed2.wav");
var sound3 = new Audio("Yeeees.wav");
var sound4 = new Audio("girl_shut_up.wav");
var sound5 = new Audio("imhmmm.wav");
var randomizer;
function playRandomSound(){
    randomizer = Math.floor(Math.random()*5);
    if (randomizer === 0){
        sound1.play();
    } else if (randomizer == 1){
        sound2.play();
    } else if (randomizer == 2){
        sound3.play();
    } else if (randomizer == 3){
        sound4.play();
    } else if (randomizer == 4){
        sound5.play();
    }
}
body {
  background: white;
}
#rokas {
  height: 100vh;
}
<HTML>
  <HEAD>
    
  </HEAD>
  <BODY>
    <img src="https://i.imgur.com/4lO3dpT.jpg" id="rokas" onclick="playRandomSound()">
  </BODY>
</HTML>

2 个答案:

答案 0 :(得分:0)

请尝试像这样更新您的代码:

html:

<audio style="display: none;" id="sound"></audio>

js:

function playRandomSound () {
  var sound = document.getElementById('sound');
  randomizer = Math.floor(Math.random()*5);

  if (randomizer === 0){
    sound.src = sound1;
  } else if (randomizer == 1){
    sound.src = sound2;
  } else if (randomizer == 2){
    sound.src = sound3;
  } else if (randomizer == 3){
    sound.src = sound4;
  } else if (randomizer == 4){
    sound.src = sound5;
  }
  sound.load();
  sound.play();  
}

希望有帮助。

答案 1 :(得分:0)

添加标签...

<audio id="audioPlaceHolder" src="InDeed.wav" autostart="false" ></audio>

您可以通过JavaScript动态更改src。

要播放...

var sound = document.getElementById('audioPlaceHolder');
sound.play();

享受!