Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect sound is ended in THREE.PositionalAudio?

I want to detect when sounds is ending, but all examples that i found not working.

// Create sound
var sound1 = new THREE.PositionalAudio( listener );
sound1.load( 'sounds/Example.ogg' );
sound1.setRefDistance( 30 );
sound1.autoplay = false;
sound1.setLoop(false);
mesh1.add( sound1 );

// Start sound
setTimeout(function() {
    sound1.play();
}, 2000);

// Try to detect end #1
sound1.onended = function() {
    console.log('sound1 ended #1');
};
// Try to detect end #1
sound1.addEventListener('ended', function() {
    console.log('sound1 ended #2');
});

Live example: http://codepen.io/anon/pen/wMRoWQ

like image 634
skywind Avatar asked Feb 10 '16 18:02

skywind


2 Answers

Three.Audio is wrapper around a buffer source audio object. https://github.com/mrdoob/three.js/blob/ddab1fda4fd1e21babf65aa454fc0fe15bfabc33/src/audio/Audio.js#L12

It looks like it overrides the onended event and binds it to its own function, so we just do the same:

sound1.source.onended = function() {
    console.log('sound1 ended');
    this.isPlaying = false; /* sets Three wrapper property correctly */
};

We set isPlaying = false because this is what Three's Audio onended function does, which we just overrode.

working pen: http://codepen.io/anon/pen/GoambE

like image 165
Tennyson H Avatar answered Nov 06 '22 13:11

Tennyson H


I just had to solve this problem in 2020. I wasn't looking at the docs right at first, but it is correctly listed, it seems.

Similar to the previously correct answer, but a bit different now (that solution did not work for me):

var sound1 = new THREE.PositionalAudio( listener );
sound1.onEnded = () => console.log("track ended")

Here's the appropriate docs: https://threejs.org/docs/#api/en/audio/Audio.onEnded

There's not much there, basically:

.onEnded () : null

Called automatically when playback finished.

Things that did not work for me:

sound1.onEnded(() => {})
el.object3D.source.onended(() => {})
sound1.source.onended(() => {}); // previous answer

If you do this, you can intercept a call, but I don't think it's necessary anymore:

  THREE.Audio.prototype.onEnded = function() {
      console.warn("arguments to onEnded!", arguments)
  };
like image 1
Kyle Baker Avatar answered Nov 06 '22 11:11

Kyle Baker