播放新音频时停止播放音频

时间:2015-08-31 04:16:57

标签: javascript jquery audio

如果按下按钮,它应播放新声音并停止正在播放的当前声音。它应该也是这样,当一个声音正在播放时,“暂停”被打开。但是如果与按钮相关的声音没有播放,则该类是正常的,即“播放”。

//this is the buttons that can be pressed to play sound
<span class="play" sound="sound1.mp3">Play</span>
<span class="play" sound="sound2.mp3">Play</span>
<span class="play" sound="sound3.mp3">Play</span>

<script>
// trying to make it so that the var audio selects sound based on what button was pressed
var audio = document.createElement('sound');
//when a button is pressed plays sound
$(".play").on('click', function(){

if (audio.paused) {
       audio.play();
    }   
    else {
       audio.pause();
    }
    $( this ).toggleClass( "pause" ); // switch to some new css for a pause button
});

// make it so if audio is already playing and another sound is pressed, the audio that is playing is stopped and newly pressed sound plays.
if any other audio is playing{
then that audio.stop and this.audio. that was clicked. play 
}
// make it so the CSS of the already playing button is switched back and the css of the new button is turned to the pause class.
$( that ).toggleClass( "play" );
$( this ).toggleClass( "pause" );
</script>

1 个答案:

答案 0 :(得分:0)

我只是将音频元素嵌入到这样的跨度中:

<span class="play"><audio src="sound1.mp3">Play</audio></span>
<span class="play"><audio src="sound2.mp3">Play</audio></span>
<span class="play"><audio src="sound3.mp3">Play</audio></span>

然后做一些jQuery魔术

$(".play").click(function () {
   $(".play").removeClass('pause').addClass('play').pause();
   $(this).addClass('pause').removeClass('play').play();
});