Last active
August 2, 2023 12:54
-
-
Save phsultan/3b38a508072d83e374cbbbcf13485f1c to your computer and use it in GitHub Desktop.
Google Speech Recognition with API key + gRPC
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Make sure you're not already authenticated with gRPC, on MacOS you need | |
* to ensure the GOOGLE_APPLICATION_CREDENTIALS environment variable is not | |
* set : `unset GOOGLE_APPLICATION_CREDENTIALS` | |
* | |
* @google-cloud/speech and google-gax are used to load the necessary .proto files | |
* | |
* I tried to add the 'key' to the request itself, or as a metadata with the request | |
* and always getting the following error from gRPC : | |
* Error: 7 PERMISSION_DENIED: The request is missing a valid API key. | |
*/ | |
var PROTO_PATH = __dirname + '/node_modules/\@google-cloud/speech/protos/google/cloud/speech/v1/cloud_speech.proto'; | |
const grpc = require('grpc'); | |
const fs = require('fs'); | |
const merge = require('lodash.merge'); | |
const gax = require('google-gax'); | |
const path = require('path'); | |
const API_KEY = 'INSERT YOUR API KEY HERE'; | |
const fileName = './audio.raw'; | |
const metadata = new grpc.Metadata(); | |
metadata.add('x-goog-api-key', API_KEY); | |
// Load the applicable protos. | |
var protos = merge( | |
{}, | |
gax.grpc().loadProto( | |
path.join(__dirname, 'node_modules', '\@google-cloud', 'speech', 'protos'), | |
'google/cloud/speech/v1/cloud_speech.proto' | |
) | |
); | |
// Reads a local audio file and converts it to base64 | |
const file = fs.readFileSync(fileName); | |
const audioBytes = file.toString('base64'); | |
// The audio file's encoding, sample rate in hertz, and BCP-47 language code | |
const audio = { | |
content: audioBytes, | |
}; | |
const config = { | |
encoding: 'LINEAR16', | |
sampleRateHertz: 16000, | |
languageCode: 'en-US', | |
}; | |
const request = { | |
audio: audio, | |
config: config, | |
key: API_KEY | |
}; | |
const client = new protos.google.cloud.speech.v1.Speech('speech.googleapis.com:443', grpc.credentials.createSsl()); | |
client.Recognize(request, | |
metadata, | |
function(err, response) { | |
if (err) { | |
console.log("ERR :", err); | |
return; | |
} | |
console.log("RESPONSE :", response); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello @phsultan,
Thank you for your answer, yes I have it in my code and its initialized
Here is the google-gax line in my package.json dependencies
Have a nice day !