Damir
Damir

Reputation: 342

Play sound a set number of times with JS player in my HTML page

I want to have the sound played 3 times and then stopped in my html page, it keeps looping if I enable loop to true or plays 1x if it's false.

My code looks like this at the moment, can someone advise?

var popupAudioPlayer = document.getElementById('popup_sound');
scene.on("enter", function (event) {
    popupAudioPlayer.currentTime = 0;
    popupAudioPlayer.loop = true;
    popupAudioPlayer.playthroughs = 3;
    popupAudioPlayer.play()
});

Upvotes: 1

Views: 1068

Answers (1)

f-CJ
f-CJ

Reputation: 4481

The html audio element does not provide any attribute to determine the number of times it should play the audio.

One way to solve it is by using a counter and attaching an event listener to the ended event of the html audio element. Every time the play finishes the event listener will be executed, where you can decrement the counter and play the audio again.

Once the counter reaches 0, you remove the event listener.

Like this:

var popupAudioPlayer = document.getElementById('popup_sound');
var scene = document.getElementById('scene');

scene.addEventListener("click", function (event) {
    let counter = 3;
    
    const customPlay = function() {      
      popupAudioPlayer.play();
      counter--;
      
      if (counter === 0) {
        popupAudioPlayer.removeEventListener('ended', customPlay);
      }
    };
    
    popupAudioPlayer.addEventListener('ended', customPlay);
    
    popupAudioPlayer.currentTime = 0;
    popupAudioPlayer.loop = false;    
    customPlay();
});
<button id="scene">
  Play me 3 times
</button>

<audio 
  id="popup_sound"
  src="https://www.soundeffectsplus.com/uploads/prod_audio/41802331_bow-arrow-hit-target-01.mp3" />

Upvotes: 1

Related Questions