Search code examples
node.jsbufferprotocol-buffersgoogle-speech-apigoogle-cloud-speech

With google cloud speech to text and the node.js SDK, How can I read the value of the Buffer?


I have a response like:

{ name: '7373656846233364184',
  metadata:
   { type_url:
      'type.googleapis.com/google.cloud.speech.v1p1beta1.LongRunningRecognizeMetadata',
     value:
      <Buffer 08 64 12 0c 08 aa 8d b2 e9 05 10 c8 a5 fc b9 02 1a 0c 08 f3 8d b2 e9 05 10 b0 f1 aa b1 02> },
  done: true,
  response:
   { type_url:
      'type.googleapis.com/google.cloud.speech.v1p1beta1.LongRunningRecognizeResponse',
     value:
      <Buffer 12 f3 01 0a e7 01 0a 27 46 6f 72 20 53 65 70 74 65 6d 62 65 72 20 31 73 74 2e 20 48 6f 77 20 64 6f 20 79 6f 75 20 72 65 67 69 73 74 65 72 3f 15 bb d9 ... > },
  result: 'response' }

I tried:

                const metadata = JSON.parse(getResponse.metadata.value.toString());
                const response = JSON.parse(getResponse.response.value.toString());

But that has an error:

Unhandled rejection SyntaxError: Unexpected token in JSON at position 0

Solution

  • This discussion resulted in a solution from Alexander Fenster. Basically:

    const protobufjs = require('protobufjs');
    
    // load proto files once. Note v1 below: if you use speech.v1p1beta1, use it in the path
    const root = protobuf.loadSync([ // note: synchronous file read - use .load() to use callback API
      './node_modules/@google-cloud/speech/protos/google/cloud/speech/v1/cloud_speech.proto',
      './node_modules/google-gax/protos/google/protobuf/timestamp.proto'
    ]);
    
    // helper function to decode google.protobuf.Any
    function decodeProtobufAny(protobufAny) {
      const typeName = protobufAny.type_url.replace(/^.*\//, '');
      const type = root.lookupType(typeName);
      return type.decode(protobufAny.value);
    }
    

    And then:

    const decodedMetadata = decodeProtobufAny(getResponse.metadata);
    const decodedResponse = decodeProtobufAny(getResponse.response);