cmb28
cmb28

Reputation: 421

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!

Upvotes: 5

Views: 8405

Answers (5)

coder618
coder618

Reputation: 1004

You need to have a service account, and service account .json key File.

You need to pass the key file name while you creating the client Instance.

const client = new textToSpeech.TextToSpeechClient({
    keyFilename: "./auth.json",
});

Download the key file and rename it as auth.json place it root of your project folder.

Make sure Your service account have proper access to call the API.

Here is the full code:

// Imports the Google Cloud client library
const textToSpeech = require("@google-cloud/text-to-speech");

// Import other required libraries
const fs = require("fs");
const util = require("util");

// Creates a client
const client = new textToSpeech.TextToSpeechClient({
    keyFilename: "./auth.json",
});
async function quickStart() {
    // The text to synthesize
    const text = "Hello this is a test";

    // Construct the request
    const request = {
        input: { text: text },

        // Select the language and SSML voice gender (optional)
        voice: { languageCode: "en-US", ssmlGender: "NEUTRAL" },
        // select the type of audio encoding
        audioConfig: { audioEncoding: "MP3" },
    };

    // Performs the text-to-speech request
    const [response] = await client.synthesizeSpeech(request);
    // Write the binary audio content to a local file
    const writeFile = util.promisify(fs.writeFile);
    await writeFile("output.mp3", response.audioContent, "binary");
    console.log("Audio content written to file: output.mp3");
}
quickStart();

Upvotes: 0

Jafar Jabr
Jafar Jabr

Reputation: 672

this seems to be an old discussion but I thought to comment, maybe someone will come across like in my case :)) for nodejs client, I managed to authenticate it this way:

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

Upvotes: 2

Augusto Ferrari
Augusto Ferrari

Reputation: 121

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)

Upvotes: 8

RaviJK
RaviJK

Reputation: 21

There are 2 ways :

1 Way : if you using Json file then better to set json path into Environment Variable, if you do this then you no need to setup in coding it will automatically get you license from there

GOOGLE_APPLICATION_CREDENTIALS=[path]

2 WAY :

I have Java code i don't know about python so you can get idea from here :

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)

Upvotes: 2

Deepen Patel
Deepen Patel

Reputation: 180

You could authenticate your google credential by different ways. One is by setting OS environment and another one is authenticate while you initiate a request.

I would suggest oauth2client library for python to authenticate. In addition to this refer my example on Github (Link).

Upvotes: 0

Related Questions