如何将凭据添加到Google文本到语音API?

时间:2018-05-21 09:18:43

标签: python-3.x google-api google-authentication google-text-to-speech

我是Python新手。我想使用Google文本转语音API,因为我使用了以下代码,但由于错误,我无法访问API。这是代码,

def synthesize_text(text):
    """Synthesizes speech from the input string of text."""
    from google.cloud import texttospeech
    client = texttospeech.TextToSpeechClient()

    input_text = texttospeech.types.SynthesisInput(text=text)

    # Note: the voice can also be specified by name.
    # Names of voices can be retrieved with client.list_voices().
    voice = texttospeech.types.VoiceSelectionParams(
        language_code='en-US',
        ssml_gender=texttospeech.enums.SsmlVoiceGender.FEMALE)

    audio_config = texttospeech.types.AudioConfig(
        audio_encoding=texttospeech.enums.AudioEncoding.MP3)

    response = client.synthesize_speech(input_text, voice, audio_config)

    # The response's audio_content is binary.
    with open('output.mp3', 'wb') as out:
        out.write(response.audio_content)
        print('Audio content written to file "output.mp3"')

这是错误,

google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or
explicitly create credential and re-run the application. For more
information, please see
https://developers.google.com/accounts/docs/application-default-credentials.

我已经拥有凭据JSON文件,但我无法配置代码来验证我的请求。 请帮忙!

4 个答案:

答案 0 :(得分:2)

您可以尝试以下代码:

public class MyFragmentPagerAdapter extends FragmentStatePagerAdapter {

    @Override
    public Fragment getItem (int position){
        switch (position) {
            case 0:
                //
            case 1:
                //
            case 2:
                return new MyFragment();
        }
        return null;
    }

    @Override
    public int getCount() {
        return 3;
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

}

答案 1 :(得分:0)

您可以通过不同方式验证您的Google凭据。 一种是通过设置OS环境而另一种是在您发起请求时进行身份验证。

我建议oauth2client库让python进行身份验证。 除此之外,请参阅我在Github上的例子(Link)。

答案 2 :(得分:0)

有2种方法:

1种方式: 如果您使用Json文件,则最好将json路径设置为环境变量,如果您这样做,则无需进行编码设置,它将自动从那里获取许可证

GOOGLE_APPLICATION_CREDENTIALS=[path]

2路:

我有我不了解python的Java代码,因此您可以从这里获得想法:

String jsonPath = "file.json"; 
 CredentialsProvider credentialsProvider = FixedCredentialsProvider.create(ServiceAccountCredentials.fromStream(new FileInputStream(jsonPath)));
TextToSpeechSettings settings = TextToSpeechSettings.newBuilder().setCredentialsProvider(credentialsProvider).build();
    Instantiates a client
TextToSpeechClient textToSpeechClient = TextToSpeechClient.create(settings)

答案 3 :(得分:0)

这似乎是一个古老的讨论,但我想发表评论,也许有人会遇到像我这样的情况:)) 对于 nodejs 客户端,我设法通过这种方式对其进行了身份验证:

const client = new textToSpeech.TextToSpeechClient({
credentials: {
private_key: "??",
client_email: "???",
 }
});