在 Safari 和 Edge 中将 Float32Array 复制到新的 AudioBuffer

Copy Float32Array to new AudioBuffer in Safari and Edge

情况如下:我需要从缓冲区中取出一个表示通道的 Float32Array,并将其复制到新的 AudioBuffer。缓冲区上的 copyToChannel 方法在这些浏览器中不可用,即使 MDN 说它应该可用。该应用程序使用该方法失败 undefined

所以我尝试了 example does to copy data from one channel array to another. But that results in SyntaxError: The string did not match the expected pattern on the OfflineAudioContext constructor which is used inside the audio-resampler package 来降低音频采样率。同样,这一切只发生在 Safari 11 和 Edge 上。但是我检查了所有进入构造函数的参数,它们都是整数。堆栈跟踪的其余部分没有给我任何其他线索。

这是我此时的代码:

this.audioRecorder.getBuffer((buffers) => {
    // `buffers` is an array of two Float32Arrays representing each channel
    // so create a new buffer and and copy the channel data to it to preserve the audio
    const _buffer = this.audioContext.createBuffer(
      1,
      buffers[0].length,
      this.audioContext.sampleRate
    )

    // _buffer.copyToChannel(buffers[0], 0, 0)

    const channelData = _buffer.getChannelData(0)
    for (let i = 0; i < channelData.length; i++) {
      channelData[i] = buffers[0][i]
    }

    resampler(_buffer, 16000, function(event) {
      const _buffer = event.getAudioBuffer()
      const audioData = {
        sampleRate: _buffer.sampleRate,
        channelData: []
      }

      if (_buffer.duration > 3.0) reject(constants.messages.sampleLength)

      for (var i = 0; i < _buffer.numberOfChannels; i++) {
        audioData.channelData[i] = _buffer.getChannelData(i)
      }

      // resolves a promise outside this code
      resolve(audioData)
    })
  })

我确实找到了 并尝试了:_buffer.getChannelData(0).set(buffers[0])。导致与上面相同的 SyntaxError。

最后,我发现了这个 webkit test .txt,它似乎暗示在将 0 传递给 OfflineAudioContext 构造函数时会抛出 SyntaxError。我在构造函数之前检查了参数,它们是所有非零

OfflineAudioContext 的参数的有效值有限制。您将必须检查实现以确定限制,但如果您可以使用这些值创建 AudioBuffer,那么您应该能够使用这些值构建 OfflineAudioContext。如果不是,那是实现中的错误。