我想检测声音何时结束,但是我发现所有示例均无效。

// 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

最佳答案

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

看起来它覆盖了onended事件并将其绑定(bind)到其自己的函数,因此我们只需执行以下操作:

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

09-07 16:29