python-3.xgoogle-apigoogle-authenticationgoogle-text-to-speech

How to add credentials to Google text to speech API?


I am new to Python.I want to use Google text-to-speech API for that i used below code, but I am unable to access the API due to error. This is the code,

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"')

This is the error,

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.

I already have credentials JSON file, but I am unable to configure the code to authenticate my request. Please help!


Solution

  • You could try this code:

    from google.oauth2 import service_account
    
    credentials = service_account.Credentials.from_service_account_file('yourkey.json')
    
    client = texttospeech.TextToSpeechClient(credentials=credentials)