block14
block14

Reputation: 619

Stop any current audio on play

I would like to have any previously played audio to be stopped before playing a new audio clip over the previous. This is to prevent double clips on elements which will play the audio file multiple times.

I tried to pause and set the current time to 0 but neither are working. What is the correct way to do this?

        $(".playAudio").on('click touchstart', function () {
            var audio = document.createElement('audio');
            audio.setAttribute('src', $(this).attr('data-audio'));
            audio.pause();
            audio.currentTime = 0;
            audio.play();
        });

Upvotes: 0

Views: 846

Answers (1)

Paul Fitzgerald
Paul Fitzgerald

Reputation: 12129

You could pause the audio clip if it exists.

The code below should work.

let audio;

$(".playAudio").on('click touchstart', function () {

   if(audio){
     audio.pause();
   }

   audio = document.createElement('audio');
   audio.setAttribute('src', $(this).attr('data-audio'));
   audio.currentTime = 0;
   audio.play();
});

Upvotes: 2

Related Questions