0

The example below from Google works but it uses pipe. For my situation I'm listening to a websocket that sends packets in 20ms increments and from what I've been able to find there is no way to pipe that data into a function.

The first argument that must be passed on initialization is a config object. After that only data is accepted. So I set the function up as a variable, then pass the config. But I can't figure out how to pass the stream of data into it afterwards. How do I pass data into recognizeStream without using pipe? Or is there are a way to use pipe with websocket

I can vouch for this setup working by reading and writing from temporary files at certain intervals but this has the obvious disadvantages of 1) all of that overhead and 2) most importantly, not being a real-time stream.

There are two solutions that I think would work but have not been able to implement:

  1. There is some way to setup a pipe from websocket (This is ideal)
  2. Simultaneously writing the data to a file while at the same time reading it back using createReadStream from a file using some implementation of fs (This seems like a minefield of problems)

tl;dr I need to send the stream of data from a websocket into a function assigned to a const as the data comes in.

Example setup from 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 setup

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

    }
  })
})
Max Phillips
  • 6,991
  • 9
  • 44
  • 71

1 Answers1

0

You should just be able to do:

recognizeStream.write(message.binaryData)
idbehold
  • 16,833
  • 5
  • 47
  • 74