三。音频-获取currentTime并设置onEnded函数

时间:2018-11-03 14:22:09

标签: javascript audio three.js

在Three.js应用程序中,我采用了一种简单的方式来加载,播放和分析音频,该方法可在台式机和移动设备上使用。必须使用THREE.Audio,因为HTML5音频分析器无法在移动设备上运行,请改为THREE.AudioAnalyser。 很高兴,除了我找不到方法:

  • 获取音频的当前播放时间
  • 设置onEnded函数

代码在这里:

function soundLoad() {
listener = new THREE.AudioListener();
audio = new THREE.Audio( listener );
audioLoader = new THREE.AudioLoader();
analyser = new THREE.AudioAnalyser( audio, 32 );
audioLoader.load( 'audio/01.mp3', function( buffer ) {
    audio.setBuffer( buffer );
    audio.setLoop( false );
    audio.setVolume( 1 );
    (function readyToGo() {
        console.log(audio.buffer.duration); // yes it works
        document.getElementById('btnPlay').addEventListener( 'click', function(){
           audio.play(); 
           setInterval(function(){
             console.log(audio.context.currentTime); // starts counting from the loading, not from the actual play
             console.log(audio.buffer.currentTime); // doesnt' work
           }, 10);
        }, false);
        // audio.onEnded = function() { console.log(‘end’);}; 
        // audio.buffer.onEnded = function() { console.log(‘end’);};
        // audio.source.onEnded = function() { console.log(‘end’);}; //none of them works
    })();
});}

希望这两个问题都有解决方案,而不必创建实际的ctx或其他第三部分。谢谢!

2 个答案:

答案 0 :(得分:1)

感谢Mugen87的提示,我已经在render函数中编写了可以满足我需要的简单行,因此请检查每一帧:

声明

var audioPrevTime, audioCurrentTime, data;

在渲染功能中:

if (pause == 0){
    audioCurrentTime = audio.context.currentTime - audio.startTime + audioPrevTime;
    if (audioCurrentTime >= audio.buffer.duration){
        console.log('end song');
    }
    data = analyser.getAverageFrequency();
} else if (pause == 1){
    audioPrevTime = audioCurrentTime;
}

在所有这几行中,所有这些功能都可以加载,播放,控制和分析台式机和移动设备上的声音(在到目前为止我测试过的设备上都不错)。

答案 1 :(得分:0)

three.js不公开Web音频事件,因此不建议覆盖AudioScheduledSourceNode.onended。这可能会产生意想不到的副作用。如果您需要音频的当前时间,则必须自己计算该值。试试这个:

const currentTime = audio.context.currentTime - audio.startTime;
相关问题