Jeff
Jeff

Reputation: 1004

Stop playing audio when new audio is played

If a button is pushed it should play the new sound and stop the current sound that is playing. it should also make it so when a sound is playing the class "pause" is toggled on. But if the sound associated with a button is not playing then the class is normal which is "play".

//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>

Upvotes: 0

Views: 1448

Answers (1)

Jack Guy
Jack Guy

Reputation: 8523

I would just embed audio elements in the spans like this:

<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>

And then do some jQuery magic

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

Upvotes: 0

Related Questions