JS - 每次点击后播放不同的声音

时间:2017-01-19 19:00:49

标签: javascript html audio onclick

我有一个链接,我希望链接在每次点击时播放不同的声音。当我点击链接时,它同时播放两种声音,但我一次只需要一个声音

var bleep = new Audio('hello.mp3') ;
bleep.src = "hello.mp3" ; 

var bleep2 = new Audio('goodbye.mp3') ;
bleep2.src = "goodbye.mp3"; 



    <a href="#" onclick="bleep.play('hello.mp3'); bleep2.play('goodbye.mp3');">Home</a>

2 个答案:

答案 0 :(得分:2)

你应该用它来制作一个能检查上次点击了哪个声音的功能。此外,您既不需要设置.src属性,也不需要将字符串传递给https://github.com/ruslo/polly

<强> JS:

var bleep = new Audio('hello.mp3');

var bleep2 = new Audio('goodbye.mp3');

var playFirst = true;
function playSound() {
  if (playFirst) {
    bleep.play();
  } else {
    bleep2.play();
  }
  playFirst = !playFirst;
}

<强> HTML:

<a href="#" onclick="playSound()">Home</a>

答案 1 :(得分:2)

不是将事件侦听器内联为onclick,而是使用addEventListener将其附加到JS。这允许您选择要播放的音频片段:

var helloSound = new Audio('hello.mp3');
helloSound.src = "hello.mp3"; 

var goodbyeSound = new Audio('goodbye.mp3');
goodbyeSound.src = "goodbye.mp3";

var homeLink = document.getElementById('home-link');

homeLink.addEventListener('click', function () {
    if (/* condition to play hello */) {
        helloSound.play();
    } else {
        goodbyeSound.play();
    }
});

标记:

<a href="#" id="home-link">Home</a>