首页 > 解决方案 > java.io.IOException:必须定义环境变量 GOOGLE_APPLICATION_CREDENTIALS 指向定义凭据的文件

问题描述

我想在和 android 应用程序中使用谷歌云语音 api,我正在关注谷歌提供的这个链接https://cloud.google.com/speech-to-text/docs/libraries#client-libraries-install-java

我已经尝试了链接https://developers.google.com/accounts/docs/application-default-credentials中提供的解决方案,但它仍然无法正常工作。

Windows 环境变量用户和系统都有 GOOGLE_APPLICATION_CREDENTIALS=C:\Users\ANSH\Downloads\credential.json

所有必要的进口都存在。

 private void recognizeSpeech(){
    try{
        SpeechClient speechClient = SpeechClient.create();
        String languageCode="en-US";
        int sampleRateHertz=16000;
        RecognitionConfig.AudioEncoding encoding = RecognitionConfig.AudioEncoding.LINEAR16;
        RecognitionConfig config =
                RecognitionConfig.newBuilder()
                        .setLanguageCode(languageCode)
                        .setSampleRateHertz(sampleRateHertz)
                        .setEncoding(encoding)
                        .build();
        Path path = Paths.get(fileName);
        byte[] data = Files.readAllBytes(path);
        ByteString content = ByteString.copyFrom(data);
        RecognitionAudio audio = RecognitionAudio.newBuilder().setContent(content).build();
        RecognizeRequest request =
                RecognizeRequest.newBuilder().setConfig(config).setAudio(audio).build();
        RecognizeResponse response = speechClient.recognize(request);
        for (SpeechRecognitionResult result : response.getResultsList()) {
            // First alternative is the most probable result
            SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
            outputText.setText(alternative.getTranscript());
        }
    }
    catch (Exception e){
        Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
    }
}

credential.json 包含使用服务帐户下载的密钥

环境变量图像

https://cloud.google.com/speech-to-text/docs/libraries提到了一个注释。

注意:Cloud Java 客户端库目前不支持 Android。

这是否意味着它不能在android studio中使用?如果是如何使用它?

标签: androidgoogle-cloud-platformspeech-to-textgoogle-cloud-speech

解决方案


您可能想查看此github 链接以查看异常是如何解决的,但请考虑 Speech To Text Client Libraries 指定不支持 Android,因为它已在评论中发布。

此外,由于您的问题是关于在 Android 应用程序中设置身份验证时的问题,我建议您使用 OAuth 2.0 客户端 ID。您需要从 Google 控制台生成OAuth 2.0 客户端 ID,然后按照Android 说明进行传递requestIdTokenrequestServerAuthCodeGoogleSignInOptions. 另外,请记住,这并不能保证 Speech API 和 Android 之间的正确集成,所以如果你得到这个工作,请与我们分享。


推荐阅读