在 Microsoft Edge 中重新采样音频,因为不支持复制到通道

resampling audio in Microsoft Edge since copyToChannel is not supported

本文关键字:因为 音频 不支持 复制 通道 采样 Edge Microsoft 新采样      更新时间:2023-09-26

我正在尝试重新采样一些音频。我有一个适用于 Chrome 和 Firefox 的功能,但它在语句的 Edge 中崩溃了

audioBuffer.copyToChannel(sampleArray,0,0);

说没有定义复制到通道。这很奇怪,因为Microsoft文档明确定义了它:https://dev.windows.com/en-us/microsoft-edge/platform/documentation/apireference/interfaces/audiobuffer/

无论如何,我正在寻找解决方法。在开发人员工具中检查 audioBuffer 对象并没有为我提供任何线索。

谢谢!

这是我的代码:

function reSample(sampleArray, targetSampleRate, onComplete) {
    // sampleArray is a Float32Array
    // targetSampleRate is an int (22050 in this case)
    // onComplete is called with the new buffer when the operation is complete
    var audioCtx = new window.AudioContext();
    var audioBuffer = audioCtx.createBuffer(1, sampleArray.length, audioCtx.sampleRate);
    audioBuffer.copyToChannel(sampleArray,0,0); // Not supported by Microsoft Edge 12, evidently.
    var channel = audioBuffer.numberOfChannels;
    var samples = audioBuffer.length * targetSampleRate / audioBuffer.sampleRate;
    var offlineContext = new window.OfflineAudioContext(channel, samples, targetSampleRate);
    var bufferSource = offlineContext.createBufferSource();
    bufferSource.buffer = audioBuffer;
    bufferSource.connect(offlineContext.destination);
    bufferSource.start(0);
    offlineContext.startRendering().then(function(renderedBuffer){
        onComplete(renderedBuffer);
    });
}

我在Edge上得到了这个:

    const offlineCtx = new OfflineAudioContext(sourceBuffer.numberOfChannels, sourceBuffer.duration *
      this.sampleRate, this.sampleRate);
    const cloneBuffer = offlineCtx.createBuffer(sourceBuffer.numberOfChannels, sourceBuffer.length, sourceBuffer.sampleRate);
    cloneBuffer.copyToChannel(sourceBuffer.getChannelData(0), 0);
    const source = offlineCtx.createBufferSource();
    source.buffer = cloneBuffer;
    offlineCtx.oncomplete = (e) => {
      const left = e.renderedBuffer.getChannelData(0);
      this.onAudioProcess(this.float32ToInt16(left, left.length), e.renderedBuffer.duration * 1000);
    };
    source.connect(offlineCtx.destination);
    source.start(0);
    offlineCtx.startRendering();
  }