Bibliotecas cliente de Text-to-Speech

En esta página, se muestra cómo comenzar a usar las bibliotecas cliente de Cloud para la API de Text-to-Speech. Las bibliotecas cliente facilitan el acceso a las APIs de Google Cloud mediante un lenguaje compatible. Puedes usar las APIs de Google Cloud directamente mediante solicitudes sin procesar al servidor, pero las bibliotecas cliente proporcionan simplificaciones que reducen de manera significativa la cantidad de código que debes escribir.

Obtén más información sobre las bibliotecas cliente de Cloud y las bibliotecas cliente de las API de Google anteriores en Explicación de las bibliotecas cliente.

Instala la biblioteca cliente

C++

Consulta Configura un entorno de desarrollo de C++ para obtener detalles sobre los requisitos de esta biblioteca cliente y, luego, instala las dependencias.

C#

Si usas Visual Studio 2017 o una versión posterior, abre la ventana del administrador de paquetes de NuGet y escribe lo siguiente:

Install-Package Google.Apis

Si usas las herramientas de la interfaz de línea de comandos de .NET Core para instalar tus dependencias, ejecuta el siguiente comando:

dotnet add package Google.Apis

Para obtener más información, consulta Configura un entorno de desarrollo de C#.

Go

go get cloud.google.com/go/texttospeech/apiv1

Para obtener más información, consulta Configura un entorno de desarrollo de Go.

Java

Si usas Maven, agrega lo siguiente al archivo pom.xml. Para obtener más información sobre las BOM, consulta Las bibliotecas de BOM de Google Cloud Platform.

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>26.34.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-texttospeech</artifactId>
  </dependency>

Si usas Gradle, agrega lo siguiente a las dependencias:

implementation 'com.google.cloud:google-cloud-texttospeech:2.38.0'

Si usas sbt, agrega lo siguiente a las dependencias:

libraryDependencies += "com.google.cloud" % "google-cloud-texttospeech" % "2.38.0"

Si usas Visual Studio Code, IntelliJ o Eclipse, puedes agregar bibliotecas cliente a tu proyecto con los siguientes complementos IDE:

Los complementos brindan funcionalidades adicionales, como administración de claves para las cuentas de servicio. Consulta la documentación de cada complemento para obtener más detalles.

Para obtener más información, consulta Configura un entorno de desarrollo de Java.

Node.js

npm install --save @google-cloud/text-to-speech

Para obtener más información, consulta Configura un entorno de desarrollo de Node.js.

PHP

composer require google/apiclient

Para obtener más información, consulta PHP en Google Cloud.

Python

pip install --upgrade google-cloud-texttospeech

Para obtener más información, consulta Configura un entorno de desarrollo de Python.

Ruby

gem install google-api-client

Para obtener más información, consulta Cómo configurar un entorno de desarrollo en Ruby.

Configura la autenticación

Para autenticar llamadas a las API de Google Cloud, las bibliotecas cliente son compatibles con las credenciales predeterminadas de la aplicación (ADC). Las bibliotecas buscan credenciales en un conjunto de ubicaciones definidas y las usan para lo siguiente: autenticar solicitudes en la API. Con ADC, puedes hacer que las credenciales estén disponibles para tu aplicación en una variedad de entornos, como el desarrollo o producción local, sin necesidad de modificar el código de la aplicación.

Para los entornos de producción, la forma en que configuras ADC depende del servicio y el contexto. Para obtener más información, consulta Configura credenciales predeterminadas de la aplicación.

Para un entorno de desarrollo local, puedes configurar ADC con las credenciales asociadas con tu cuenta de Google:

  1. Instala e inicializa gcloud CLI

    Cuando inicialices gcloud CLI, asegúrate de especificar un proyecto de Google Cloud en el que tengas permiso para acceder a los recursos que necesita tu aplicación.

  2. Crea tu archivo de credenciales:

    gcloud auth application-default login

    Aparecerá una pantalla de acceso. Después de acceder, tus credenciales se almacenan en el archivo de credenciales local que usa ADC.

Usa la biblioteca cliente

El siguiente ejemplo muestra cómo usar la biblioteca cliente.

C++


#include "google/cloud/texttospeech/v1/text_to_speech_client.h"
#include <iostream>

auto constexpr kText = R"""(
Four score and seven years ago our fathers brought forth on this
continent, a new nation, conceived in Liberty, and dedicated to
the proposition that all men are created equal.)""";

int main(int argc, char* argv[]) try {
  if (argc != 1) {
    std::cerr << "Usage: " << argv[0] << "\n";
    return 1;
  }

  namespace texttospeech = ::google::cloud::texttospeech_v1;
  auto client = texttospeech::TextToSpeechClient(
      texttospeech::MakeTextToSpeechConnection());

  google::cloud::texttospeech::v1::SynthesisInput input;
  input.set_text(kText);
  google::cloud::texttospeech::v1::VoiceSelectionParams voice;
  voice.set_language_code("en-US");
  google::cloud::texttospeech::v1::AudioConfig audio;
  audio.set_audio_encoding(google::cloud::texttospeech::v1::LINEAR16);

  auto response = client.SynthesizeSpeech(input, voice, audio);
  if (!response) throw std::move(response).status();
  // Normally one would play the results (response->audio_content()) over some
  // audio device. For this quickstart, we just print some information.
  auto constexpr kWavHeaderSize = 48;
  auto constexpr kBytesPerSample = 2;  // we asked for LINEAR16
  auto const sample_count =
      (response->audio_content().size() - kWavHeaderSize) / kBytesPerSample;
  std::cout << "The audio has " << sample_count << " samples\n";

  return 0;
} catch (google::cloud::Status const& status) {
  std::cerr << "google::cloud::Status thrown: " << status << "\n";
  return 1;
}

Go


// Command quickstart generates an audio file with the content "Hello, World!".
package main

import (
	"context"
	"fmt"
	"io/ioutil"
	"log"

	texttospeech "cloud.google.com/go/texttospeech/apiv1"
	"cloud.google.com/go/texttospeech/apiv1/texttospeechpb"
)

func main() {
	// Instantiates a client.
	ctx := context.Background()

	client, err := texttospeech.NewClient(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	// Perform the text-to-speech request on the text input with the selected
	// voice parameters and audio file type.
	req := texttospeechpb.SynthesizeSpeechRequest{
		// Set the text input to be synthesized.
		Input: &texttospeechpb.SynthesisInput{
			InputSource: &texttospeechpb.SynthesisInput_Text{Text: "Hello, World!"},
		},
		// Build the voice request, select the language code ("en-US") and the SSML
		// voice gender ("neutral").
		Voice: &texttospeechpb.VoiceSelectionParams{
			LanguageCode: "en-US",
			SsmlGender:   texttospeechpb.SsmlVoiceGender_NEUTRAL,
		},
		// Select the type of audio file you want returned.
		AudioConfig: &texttospeechpb.AudioConfig{
			AudioEncoding: texttospeechpb.AudioEncoding_MP3,
		},
	}

	resp, err := client.SynthesizeSpeech(ctx, &req)
	if err != nil {
		log.Fatal(err)
	}

	// The resp's AudioContent is binary.
	filename := "output.mp3"
	err = ioutil.WriteFile(filename, resp.AudioContent, 0644)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Audio content written to file: %v\n", filename)
}

Java

// Imports the Google Cloud client library
import com.google.cloud.texttospeech.v1.AudioConfig;
import com.google.cloud.texttospeech.v1.AudioEncoding;
import com.google.cloud.texttospeech.v1.SsmlVoiceGender;
import com.google.cloud.texttospeech.v1.SynthesisInput;
import com.google.cloud.texttospeech.v1.SynthesizeSpeechResponse;
import com.google.cloud.texttospeech.v1.TextToSpeechClient;
import com.google.cloud.texttospeech.v1.VoiceSelectionParams;
import com.google.protobuf.ByteString;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * Google Cloud TextToSpeech API sample application. Example usage: mvn package exec:java
 * -Dexec.mainClass='com.example.texttospeech.QuickstartSample'
 */
public class QuickstartSample {

  /** Demonstrates using the Text-to-Speech API. */
  public static void main(String... args) throws Exception {
    // Instantiates a client
    try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) {
      // Set the text input to be synthesized
      SynthesisInput input = SynthesisInput.newBuilder().setText("Hello, World!").build();

      // Build the voice request, select the language code ("en-US") and the ssml voice gender
      // ("neutral")
      VoiceSelectionParams voice =
          VoiceSelectionParams.newBuilder()
              .setLanguageCode("en-US")
              .setSsmlGender(SsmlVoiceGender.NEUTRAL)
              .build();

      // Select the type of audio file you want returned
      AudioConfig audioConfig =
          AudioConfig.newBuilder().setAudioEncoding(AudioEncoding.MP3).build();

      // Perform the text-to-speech request on the text input with the selected voice parameters and
      // audio file type
      SynthesizeSpeechResponse response =
          textToSpeechClient.synthesizeSpeech(input, voice, audioConfig);

      // Get the audio contents from the response
      ByteString audioContents = response.getAudioContent();

      // Write the response to the output file.
      try (OutputStream out = new FileOutputStream("output.mp3")) {
        out.write(audioContents.toByteArray());
        System.out.println("Audio content written to file \"output.mp3\"");
      }
    }
  }
}

Node.js

// 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();
async function quickStart() {
  // The text to synthesize
  const text = 'hello, world!';

  // 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();

Python

"""Synthesizes speech from the input string of text or ssml.
Make sure to be working in a virtual environment.

Note: ssml must be well-formed according to:
    https://www.w3.org/TR/speech-synthesis/
"""
from google.cloud import texttospeech

# Instantiates a client
client = texttospeech.TextToSpeechClient()

# Set the text input to be synthesized
synthesis_input = texttospeech.SynthesisInput(text="Hello, World!")

# Build the voice request, select the language code ("en-US") and the ssml
# voice gender ("neutral")
voice = texttospeech.VoiceSelectionParams(
    language_code="en-US", ssml_gender=texttospeech.SsmlVoiceGender.NEUTRAL
)

# Select the type of audio file you want returned
audio_config = texttospeech.AudioConfig(
    audio_encoding=texttospeech.AudioEncoding.MP3
)

# Perform the text-to-speech request on the text input with the selected
# voice parameters and audio file type
response = client.synthesize_speech(
    input=synthesis_input, voice=voice, audio_config=audio_config
)

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

Recursos adicionales

C++

La siguiente lista contiene vínculos a más recursos relacionados con la biblioteca cliente para C++:

C#

La siguiente lista contiene vínculos a más recursos relacionados con la biblioteca cliente para C#:

Go

En la siguiente lista, se incluyen vínculos a más recursos relacionados con la biblioteca cliente para Go:

Java

La siguiente lista contiene vínculos a más recursos relacionados con la biblioteca cliente para Java:

Node.js

La siguiente lista contiene vínculos a más recursos relacionados con la biblioteca cliente de Node.js:

PHP

La siguiente lista contiene vínculos a más recursos relacionados con la biblioteca cliente para PHP:

Python

La siguiente lista contiene vínculos a más recursos relacionados con la biblioteca cliente para Python:

Ruby

La siguiente lista contiene vínculos a más recursos relacionados con la biblioteca cliente para Ruby: