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

问题描述 投票:0回答:2

我是Python的新手。我想使用谷歌的文本到语音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文件,但我无法配置代码来验证我的请求。请帮忙!

python-3.x google-api google-authentication google-text-to-speech
2个回答
2
投票

你可以尝试这段代码:

from google.oauth2 import service_account

credentials = service_account.Credentials.from_service_account_file('yourkey.json')

texttospeech.TextToSpeechClient(credentials=credentials)

0
投票

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

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


0
投票

有两种方式:

1方式:如果您使用Json文件,那么最好将json路径设置为环境变量,如果您这样做,那么您不需要设置编码它将自动从那里获得许可

GOOGLE_APPLICATION_CREDENTIALS=[path]

2种方法 :

我有Java代码,我不知道python,所以你可以从这里得到的想法:

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)
© www.soinside.com 2019 - 2024. All rights reserved.