按下按钮时显示声音名称

时间:2016-12-11 02:52:07

标签: javascript html

所以我有一个按钮,按下它会发出随机声音。我希望能够根据正在播放的声音显示某个文本。我需要一些帮助,因为我对这些东西很陌生。

这里是html

<a href="#" onclick="mySounds()" id="soundbutton" class="button button1"></a>
<script type="text/javascript" src="meme.js"></script></div>

这是Javascript

var sounds = ["Titanic.mp3",
"biggiecheese.mp3",
"mcscuseme.mp3",
"orgasm.mp3",
"broccoli.mp3",
"crab.mp3",
"sniffing.mp3",
"criminal.mp3",
"suicidal.mp3",
"arrow.mp3",
"r2d2.mp3",
"carlwheezer.mp3",
"banana.mp3",
"blaster.mp3"


/*".mp3",*/

];

var sound;

//function used to create a random number
function generateRandomNumber(max) {
  return Math.floor(Math.random() * max);
}

function playSound() {
  //create a random number and assign to x
  var x = generateRandomNumber(sounds.length - 1);
  var soundSrc = sounds[x];
  //create a new instance of the audio object
  if (sound) {
      sound.pause();
  } else {
  sound = new Audio();
  }
  sound.src = soundSrc;
  //play the sound
  sound.play();
}

document.getElementById('soundbutton').addEventListener('click', playSound);

1 个答案:

答案 0 :(得分:0)

只需在onClick侦听器上设置声音名称的任何元素。

<span id='myspan'></span>
<script>
    function playSound() {
      ...
      document.getElementById('myspan').innerHTML = sound.src;
    }
</script>

另外,正如Brimstone所说,你不需要最后一行,因为链接被绑定到定义中的监听器。

document.getElementById('soundbutton').addEventListener('click', playSound);