节点流:如何转换 Buffer 流以将数组写入输出

问题描述

我有一个包含缓冲区数据(音频样本)的 readableStream。
在我的自定义转换中,我读取字节并将音频缓冲区分离到单独的通道 (L/R) 中。

我希望下一个流消费者接收这些转换后的数组以进行进一步的操作。
当我尝试这样做时,它会引发错误TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer. Received an instance of Array

我认为 readableObjectModewritableObjectMode 会有所帮助,但这并不能解决问题。

知道我如何解决这个问题吗?

// Setup the transform
const extractChannels = new ExtractChannelsTransform(
  this.sampleFormat
)

this.stream
  .pipe(extractChannels)
  .pipe(process.stdout)


// ExtractChannelsTransform class
class ExtractChannelsTransform extends Transform {

  constructor(sampleFormat) {
    super({
      objectMode: true,readableObjectMode: false,writableObjectMode: true
    })
  }

  _transform(chunk,encoding,callback) {

    const channels = ... // chunk bytes are read here and transformed into an array per channel

    callback(null,channels)
  }

}

解决方法

将输出块(通道)转换为关于错误消息的字符串或缓冲区。

https://nodejs.org/api/stream.html#stream_stream

Node.js API 创建的所有流都只对字符串和 Buffer(或 Uint8Array)对象进行操作。