检测声音在THREE.PositionalAudio中结束?

时间:2016-02-10 18:25:02

标签: javascript audio three.js

我想检测声音何时结束,但我发现所有不能正常工作的例子。

// 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');
});

实例: http://codepen.io/anon/pen/wMRoWQ

2 个答案:

答案 0 :(得分:5)

Three.Audio是缓冲区源音频对象的包装。 https://github.com/mrdoob/three.js/blob/ddab1fda4fd1e21babf65aa454fc0fe15bfabc33/src/audio/Audio.js#L12

看起来它会覆盖onended事件并将其绑定到自己的函数,所以我们也是这样做的:

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

我们设置了isPlaying = false,因为这就是我们刚刚覆盖的Three's Audio onended function does

工作笔:http://codepen.io/anon/pen/GoambE

答案 1 :(得分:1)

我只需要在 2020 年解决这个问题。一开始我没有正确查看文档,但它似乎已正确列出。

类似于以前的正确答案,但现在有点不同(该解决方案对我不起作用):

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

以下是相应的文档:https://threejs.org/docs/#api/en/audio/Audio.onEnded

基本上没有太多内容:

<块引用>

.onEnded() : 空

播放完成后自动调用。

对我不起作用的事情:

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

如果你这样做,你可以拦截一个电话,但我认为没有必要了:

  THREE.Audio.prototype.onEnded = function() {
      console.warn("arguments to onEnded!", arguments)
  };