使用 google 云语音转文本和 node.js SDK,如何读取缓冲区的值?

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

我的回复如下:

{ 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' }

我试过了:

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

但是有一个错误:

Unhandled rejection SyntaxError: Unexpected token in JSON at position 0

This discussion resulted in a solution from Alexander Fenster。基本上:

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);
}

然后:

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