如何将数据流传输到分配给常量的函数中?

How to pipe a data stream into a function that's assigned to a constant?

下面来自 Google 的示例有效,但它使用了 pipe。对于我的情况,我正在收听一个 websocket,它以 20 毫秒的增量发送数据包,从我能够发现的情况来看,没有办法 pipe 将该数据转换为函数。

初始化时必须传递的第一个参数是 config 对象。之后只接受数据。所以我将函数设置为变量,然后传递配置。但我无法弄清楚之后如何将数据流传递给它。如何在不使用 pipe 的情况下将数据传递到 recognizeStream?或者有没有办法将 pipewebsocket

一起使用

我可以通过以特定时间间隔从临时文件读取和写入来保证此设置的工作,但这有明显的缺点 1) 所有这些开销和 2) 最重要的是,不是实时流。

有两个我认为可行但未能实施的解决方案:

  1. 有一些方法可以从 websocket 设置 pipe(这很理想)
  2. 同时将数据写入文件,同时使用 createReadStream 从使用 fs 的某种实现的文件中读回数据(这似乎是问题的雷区)

tl;dr 我需要在数据进入时将来自 websocket 的数据流发送到分配给 const 的函数中。

示例设置来自 Google Docs

const Speech = require('@google-cloud/speech');

// Instantiates a client
const speech = Speech();

// The encoding of the audio file, e.g. 'LINEAR16'
const encoding = 'LINEAR16';

// The sample rate of the audio file, e.g. 16000
const sampleRate = 16000;

const request = {
  config: {
    encoding: encoding,
    sampleRate: sampleRate
  }
};

const recognizeStream = speech.createRecognizeStream(request)
  .on('error', console.error)
  .on('data', (data) => process.stdout.write(data.results));

// Start recording and send the microphone input to the Speech API
record.start({
  sampleRate: sampleRate,
  threshold: 0
}).pipe(recognizeStream);

Websocket 设置

const WebSocketServer = require('websocket').server
wsServer.on('connect', (connection) => {

  connection.on('message', (message) => {

    if (message.type === 'utf8') {

      console.log(message.utf8Data)

    } else if (message.type === 'binary') {

       // send message.binaryData to recognizeStream

    }
  })
})

你应该能够做到:

recognizeStream.write(message.binaryData)