J.Jacobs
J.Jacobs

Reputation: 772

A-frame sound : How to react to the end of the sound?

Loop false, poolsize 1.

Running sound.playSound() successfully plays the sound, but sound.isPlaying remains true even after the full sound has been played.

Already tried adding the 'sound-ended' event listener on the entity but it doesn't trigger neither.

There must be a proper state somewhere... right ?

Upvotes: 0

Views: 196

Answers (1)

Piotr Adam Milewski
Piotr Adam Milewski

Reputation: 14655

You can track the state of the sound component by listening to the sound-ended event. Below, click the button to play a sound, it will remain red until the audio track is over.

<script src="https://aframe.io/releases/1.3.0/aframe.min.js"></script>
<script>
  AFRAME.registerComponent("foo", {
    init: function() {
      const soundComp = this.el.components.sound; // grab the `sound` component
       
      // play the sound when the user clicks the button
      this.el.addEventListener("click", evt => {               
        this.el.setAttribute("color", "red") // turn the button red
        soundComp.playSound(); // playsound
      })

      // catch the `sound-ended` event
      this.el.addEventListener("sound-ended", evt => {
        this.el.setAttribute("color", "green") // turn it back to green
      })
    }
  })
</script>
<a-scene cursor="rayOrigin: mouse" raycaster="objects: a-sphere">
  <a-assets>
    <audio id="ding" crossorigin="anonymous" src="https://gftruj.github.io/webzamples/arjs/sound/sound/Ding-sound-effect.mp3" preload="auto"></audio>
  </a-assets>
  <a-sphere position="0 1 -3" radius="0.25" color="green" sound="src: #ding; autoplay: false" foo ></a-sphere>
</a-scene>

Upvotes: 1

Related Questions