使用按钮播放音频,并再次单击该按钮重新开始

时间:2019-10-13 08:43:31

标签: javascript html

我正在制作多个按钮,如果单击该按钮,则每个按钮都会播放指定的声音,如果单击另一个按钮并播放该声音,则停止播放声音。如果我再次单击该按钮,声音将重复到开头。谢谢:)

javascript 
$(document).ready(function(){

    $('#menuIcon').mouseover(function(e) {
    $('.bar1').addClass("hovered");
    $('.bar2').addClass("hovered");
    $('.bar3').addClass("hovered");
  });
  $('#menuIcon').mouseout(function () {
    $(".bar1").removeClass("hovered");
    $(".bar2").removeClass("hovered");
    $(".bar3").removeClass("hovered");
  });



  });

  function myFunction(x) {
    x.classList.toggle("change");
    $('.dropdown-menu').toggle();
  }


  function playSound() {
    var sound= new Audio('sound campaign/10,000 Reasons.mp3');
   sound.currentTime = 0
        sound.play();
    }

HTML

<input type="button" value="10,000 Reasons" onclick="playSound()" />

1 个答案:

答案 0 :(得分:0)

您应该使用sound.pause();暂停它。 如果要使用多种音频,则应使用HTML音频标签。 它可以让您一次暂停所有这些。
例:

<input type="button" value="10,000 Reasons" onclick="playSound(0)" />

<audio src="sound campaign/10,000 Reasons.mp3" autoplay loop>
</audio>

function playSound(e) {
 var sounds = document.getElementsByTagName('audio');
  for(i=0; i<sounds.length; i++) sounds[i].pause();
 var sounds = document.getElementsByTagName('audio')[e];

   sound.currentTime = 0
        sound.play();
    }