问题
I am trying to do some test using the Google Speech API but from outside Google Cloud. In the older beta version I was able to specify a credentials file but now I am unable to find this option in the SpeechClient
class.
How can I go about specifying the authentication keys using the Google Speech API Java library?
回答1:
Some of the classes from Frank's answer are now deprecated. This is an update to his answer.
CredentialsProvider credentialsProvider = FixedCredentialsProvider.create(ServiceAccountCredentials.fromStream(new FileInputStream("path/to/service-account.json")));
SpeechSettings settings = SpeechSettings.newBuilder().setCredentialsProvider(credentialsProvider).build();
SpeechClient speechClient = SpeechClient.create(settings);
回答2:
Follow-up from issue sent here: https://github.com/GoogleCloudPlatform/java-docs-samples/issues/697#issuecomment-309696984
The way to pass a service account to the SpeechClient is by using the following flow:
CredentialsProvider credentialsProvider = FixedCredentialsProvider.create(ServiceAccountCredentials.fromStream(new FileInputStream("/path/to/service-account.json")));
ChannelProvider channelProvider = SpeechSettings.defaultChannelProviderBuilder().setCredentialsProvider(credentialsProvider).build();
SpeechSettings settings = SpeechSettings.defaultBuilder().setChannelProvider(channelProvider).build();
// Instantiates a client
SpeechClient speech = SpeechClient.create(settings);
回答3:
I ended up using a post request with base64 of the audio file then added the Google api key in the request.
var base64 = Convert.ToBase64String(File.ReadAllBytes(file));
dynamic request = new
{
config = new
{
encoding = "LINEAR16",
sampleRateHertz = 8000,
languageCode = "en-US",
enableWordTimeOffsets = false
},
audio = new
{
content = base64
}
};
var json = JsonConvert.SerializeObject(request);
var requestJson = StringContent(json, Encoding.UTF8, "application/json");
var client = new HttpClient();
var speechToText = "";
var response = await client.PostAsync($"https://speech.googleapis.com/v1/speech:recognize?key=GOOGLE-KEY", requestJson);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var converted = JsonConvert.DeserializeObject<GcpSpeechApiResponseModel>(content);
if (converted != null) {
foreach (var result in converted.Results)
{
foreach (var alternative in result.Alternatives)
{
speechToText = speechToText + alternative.Transcript;
}
}
}
}
return speechToText;
来源:https://stackoverflow.com/questions/44409570/google-speech-api-credentials