播放和暂停播放声音

时间:2016-01-21 08:12:58

标签: javascript html button audio

我试图拥有这4个按钮,在代码中添加以便在以后修改第5个按钮,但是你可以忽略那个atm。我想要的是,当我点击一个按钮时它会播放声音,但如果我点击另一个按钮,它会暂停当前声音并播放新声音。我似乎没有让它发挥作用。

CODE:

add-migration FilePaths

2 个答案:

答案 0 :(得分:0)

var audio1 = document.getElementById('sound1');
var audio2 = document.getElementById('sound2');
var audio3 = document.getElementById('sound3');
var audio4 = document.getElementById('sound4');

var current = "";

var playSound = function(soundNumber){
    switch(soundNumber)
      {
        case 1:
          audio1.play();
          audio2.pause();
          audio3.pause();
          audio4.pause();
          break;
        case 2:
          audio1.pause();
          audio2.play();
          audio3.pause();
          audio4.pause();
          break;
        case 3:
          audio1.pause();
          audio2.pause();
          audio3.play();
          audio4.pause();
          break;
        case 4:
          audio1.pause();
          audio2.pause();
          audio3.pause();
          audio4.play();
          break;
        default:
          var audio = document.getElementById("sound"+soundNumber);
          audio.play();
          audio1.pause();
          audio2.pause();
          audio3.pause();
          audio4.pause();
          break;
      }
}
<audio id="sound1" src="monkey.mp3"></audio>
<audio id="sound2" src="sounds/sound2.mp3"></audio>
<audio id="sound3" src=".mp3"></audio>
<audio id="sound4" src=".mp3"></audio>
<audio id="sound5" src=".mp3"></audio>

<button onclick="playSound(1)">Sound 1</button><br />
<button onclick="playSound(2)">Sound 2</button><br />
<button onclick="playSound(3)">Sound 3</button><br />
<button onclick="playSound(4)">Sound 4</button><br />
<button onclick="playSound(5)">Sound 5</button><br />

按钮°5应与默认开关盒一起使用。如果您必须一般性地添加按钮,则必须更改您的功能。

答案 1 :(得分:0)

你可以用真正的短代码使用jQuery。

首先。设置指向音频元素id

data-属性

<button data-audio="sound1">Sound 1</button>

然后绑定事件。

$('button[data-audio]').click(function(){
    $current = $('#' + $(this).attr('data-audio'))[0];
    /* check all audio elements */
    $('audio').each(function(){
        if(this != $current)
            this.pause();
        else
            this.play();
    });
});

Fiddle