How do I set credentials for google speech to text

2019-08-25 02:56发布

问题:

There is C# example client-libraries-usage-csharp of using the lib.

And there is example how to set an evironment variable

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"

How do I set credentials for google speech to text without setting environment variable?

Somehow like this:

var credentials = ...create(file.json); var speech = SpeechClient.Create(credentials);

回答1:

using Grpc.Auth;

then

string keyPath = "key.json";

GoogleCredential googleCredential;
using (Stream m = new FileStream(keyPath, FileMode.Open))
    googleCredential = GoogleCredential.FromStream(m);
var channel = new Grpc.Core.Channel(SpeechClient.DefaultEndpoint.Host,
    googleCredential.ToChannelCredentials());
var speech = SpeechClient.Create(channel);


回答2:

Unless you're running your application on a GCP service, there's no other way to obtain Service Account credentials for client libraries than to set the environmental variable.

GCP client libraries use a strategy called Application Default Credentials (ADC) to find your application's credentials.

By default, the client library will use the JSON pointed to by the environmental variable. If the JSON is not found but your app is running on App Engine, Compute Engine or Kubernetes Engine, then your application will use the credentials of the default service account (for example, the App Engine default service account, if your application is running on App Engine.)