当audioContext.destination在Web Audio API中不播放声音时如何监听

时间:2015-11-16 15:07:25

标签: javascript angularjs audio web-audio audiocontext

我正在使用$timeout角度函数每512毫秒调用tick()以播放我的音频队列中的数据。我正在使用它来执行实时音频流。有时声音有一些削减,我真的需要在发出和接收声音之间保持一秒的增量。所以我想删除队列中与每次剪辑持续时间相对应的一些音频数据。

你知道是否有办法在audioContext.destination上听这些剪辑:

audioContext.destination.oncuts = function(duration) {
    audioQueue.read(duration);
});

这是我的tick和audioQueue函数:

var tick = function() {
    $scope.soundclock = Date.now();
    $timeout(tick, $scope.tickInterval);
    if(startStream && isFocused) {
        if(isChrome === true || isOpera === true || isIE === true || isFirefox === true) {
            if(audioQueue.length()>=size) {
                float32 = audioQueue.read(size);
                source = audioContext.createBufferSource();
                audioBuffer = audioContext.createBuffer(1, size, sampleRate);
                data = audioBuffer.getChannelData(0);
                for(var i=0; i<size;i++) {
                    data[i] = float32[i];
                }
                source.buffer = audioBuffer;
                source.connect(audioContext.destination);
                source.start(0);
            }
        }
        if(isSafari === true) {
            if(audioQueue.length()>=size) {
                float32 = audioQueue.read(size);
                source = audioContext.createBufferSource();
                audioBuffer = audioContext.createBuffer(1, size, sampleRate);
                data = audioBuffer.getChannelData(0);
                for(var j=0; j<size;j++) {
                    data[j] = float32[j];
                }
                source.buffer = audioBuffer;
                source.connect(audioContext.destination);
                source.noteOn(0);
            }
        }
    }
};

var audioQueue = {
    buffer: new Float32Array(0),

    write: function(newAudio){
        currentQLength = this.buffer.length;
        newBuffer = new Float32Array(currentQLength+newAudio.length);
        d = Date.now() - date;
        console.log('Queued '+newBuffer.length+' samples. ');
        date = Date.now();
        newBuffer.set(this.buffer, 0);
        newBuffer.set(newAudio, currentQLength);
        this.buffer = newBuffer;
    },

    read: function(nSamples){
        samplesToPlay = this.buffer.subarray(0, nSamples);
        this.buffer = this.buffer.subarray(nSamples, this.buffer.length);
        console.log('Queue at '+this.buffer.length+' samples. ');
        return samplesToPlay;
    },

    length: function(){
        return this.buffer.length;
    }
};

1 个答案:

答案 0 :(得分:1)

您需要不依赖于Javascript计时器(出于音频目的,非常不准确)并提前计划您的滴答声。看看我前一段时间写的关于调度计时器的http://www.html5rocks.com/en/tutorials/audio/scheduling/