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

How to add credentials to Google text to speech API?

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

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

我建议 oauth2client 库 python 进行身份验证。 除此之外,请参考我在 Github (Link).

上的示例

您可以试试这个代码:

from google.oauth2 import service_account

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

client = texttospeech.TextToSpeechClient(credentials=credentials)

有两种方式:

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)

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

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