如何获取AudioBufferSourceNode的当前时间?

und*_*ned 7 javascript web-audio-api

在使用音频元素(<audio>)或contexts(AudioContext)时,您可以检查它们的currentTime属性以确切了解缓冲区的播放时间。

在我一次创建多个源(或AudioBufferSourceNode)之前,所有这些都是不错的选择AudioContext

音源可以在不同的时间播放,因此我需要知道它们对应currentTime的,以说明:

与播放时间未知的音源关联的音频上下文。

一些基础代码供您解决:

buffer1 = [0,1,0]; //not real buffers
buffer2 = [1,0,1];

ctx = new AudioContext();

source1 = ctx.createBufferSourceNode();
source1.buffer = buffer1;
source1.connect(ctx.destination);
source1.start(0);

source2 = ctx.createBufferSourceNode();
source2.buffer = buffer2;
source2.connect(ctx.destination);
setTimeout(1000/*some time later*/){
    source2.start(0);
}

setTimeout(1500/*some more time later*/){
    getCurrentTime();
}

function getCurrentTime(){
    /* magic */
    /* more magic */
    console.log("the sources currentTime values are obviously 1500 (source1) and 500 (source2).");
}
Run Code Online (Sandbox Code Playgroud)

imc*_*mcg 7

我通常要做的是为音频源节点创建一个包装,以跟踪播放状态。我试图最小化下面的代码以显示基础知识。

核心思想是跟踪声音的开始时间和声音“暂停”的时间,并使用这些值来获取当前时间并从暂停的位置恢复播放。

在Codepen上放了一个工作示例

function createSound(buffer, context) {
    var sourceNode = null,
        startedAt = 0,
        pausedAt = 0,
        playing = false;

    var play = function() {
        var offset = pausedAt;

        sourceNode = context.createBufferSource();
        sourceNode.connect(context.destination);
        sourceNode.buffer = buffer;
        sourceNode.start(0, offset);

        startedAt = context.currentTime - offset;
        pausedAt = 0;
        playing = true;
    };

    var pause = function() {
        var elapsed = context.currentTime - startedAt;
        stop();
        pausedAt = elapsed;
    };

    var stop = function() {
        if (sourceNode) {          
            sourceNode.disconnect();
            sourceNode.stop(0);
            sourceNode = null;
        }
        pausedAt = 0;
        startedAt = 0;
        playing = false;
    };

    var getPlaying = function() {
        return playing;
    };

    var getCurrentTime = function() {
        if(pausedAt) {
            return pausedAt;
        }
        if(startedAt) {
            return context.currentTime - startedAt;
        }
        return 0;
    };

    var getDuration = function() {
      return buffer.duration;
    };

    return {
        getCurrentTime: getCurrentTime,
        getDuration: getDuration,
        getPlaying: getPlaying,
        play: play,
        pause: pause,
        stop: stop
    };
}
Run Code Online (Sandbox Code Playgroud)

  • 因此,这唯一的工作是您始终以相同的`playbackRate`进行回放。WebAudio规范中存在一个向AudioBuffer添加`playbackPosition`参数的问题。https://github.com/WebAudio/web-audio-api/issues/296 (2认同)