低延迟音频播放?

时间:2014-04-08 14:23:19

标签: javascript html5 webkitaudiocontext

使用HTML5可以实现低延迟音频播放吗?我目前正在使用AudioContext API。但是,我的延迟时间约为4秒。这对我的用例来说很重要。

    if (!window.audioContextInstance) {
      window.audioContextInstance = new webkitAudioContext();
    }
    var context = window.audioContextInstance;

    context.sampleRate = 48000;

    var buffers = [];

    var src = new Float32Array();
    var srcIdx = 0;
    var bufferSize = 2048;

    var sourceNode = context.createScriptProcessor(bufferSize, 1, 2);
    sourceNode.onaudioprocess = function(evt) {
      var c0 = evt.outputBuffer.getChannelData(0);
      var c1 = evt.outputBuffer.getChannelData(1);

      var sample = 0;

      while(sample < bufferSize) {
        if (srcIdx >= src.length) {
          if (!buffers.length) {
            console.log("Warning: Audio Buffer Underflow")
            return;
          }
          src = buffers.shift();
          srcIdx = 0;
        }

        while(sample < bufferSize && srcIdx < src.length) {
          c0[sample] = src[srcIdx++];
          c1[sample] = src[srcIdx++];
          sample++;
        }
      }
    };

    scope.$on('frame', function (event, frame) {          

      while (buffers.length > 1) {
        buffers.shift();
      }

        buffers.push(new Float32Array(frame.data));

      if (buffers.length > 0) {
        sourceNode.connect(context.destination);
      }
    });
  }

1 个答案:

答案 0 :(得分:1)

您可能对riffwave.js感兴趣,这似乎远低于4秒延迟。