Librerie client di Text-to-Speech

Questa pagina mostra come iniziare a utilizzare le librerie client di Cloud per l'API Text-to-Speech. Le librerie client semplificano l'accesso le API Google Cloud da un linguaggio supportato. Sebbene tu possa utilizzare direttamente le API Google Cloud inviando richieste non elaborate al server, le librerie client offrono semplificazioni che riducono notevolmente la quantità di codice da scrivere.

Scopri di più sulle librerie client di Cloud e le librerie client precedenti delle API di Google Spiegazione delle librerie client.

installa la libreria client

C++

Consulta Configurazione di un ambiente di sviluppo C++. per maggiori dettagli sui requisiti di questa libreria client e installa le dipendenze.

C#

Se si utilizza Visual Studio 2017 o versione successiva, apri la finestra del gestore di pacchetti Nuget e digita quanto segue:

Install-Package Google.Apis

Se utilizzi gli strumenti di interfaccia a riga di comando .NET Core per installare le dipendenze, esegui questo comando:

dotnet add package Google.Apis

Per ulteriori informazioni, consulta la sezione Configurazione di un ambiente di sviluppo C#.

Go

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

Per ulteriori informazioni, vedi Configurare un ambiente di sviluppo Go.

Java

If you are using Maven, add the following to your pom.xml file. For more information about BOMs, see The Google Cloud Platform Libraries BOM.

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

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

If you are using Gradle, add the following to your dependencies:

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

If you are using sbt, add the following to your dependencies:

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

If you're using Visual Studio Code, IntelliJ, or Eclipse, you can add client libraries to your project using the following IDE plugins:

The plugins provide additional functionality, such as key management for service accounts. Refer to each plugin's documentation for details.

Per ulteriori informazioni, consulta la sezione Configurazione di un ambiente di sviluppo Java.

Node.js

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

Per ulteriori informazioni, consulta la sezione Configurare un ambiente di sviluppo Node.js.

PHP

composer require google/apiclient

Per ulteriori informazioni, consulta Utilizzare PHP su Google Cloud.

Python

pip install --upgrade google-cloud-texttospeech

Per ulteriori informazioni, consulta Configurare un ambiente di sviluppo Python.

Ruby

gem install google-api-client

Per ulteriori informazioni, consulta Configurare un ambiente di sviluppo Ruby.

Configura l'autenticazione

Per autenticare le chiamate alle API Google Cloud, le librerie client supportano le credenziali predefinite dell'applicazione (ADC). Le librerie cercano le credenziali in un insieme di posizioni definite e le utilizzano per autenticare le richieste all'API. Con ADC, puoi le credenziali disponibili per l'applicazione in diversi ambienti, ad esempio sviluppo o produzione, senza dover modificare il codice dell'applicazione.

Per gli ambienti di produzione, il modo in cui configuri l'ADC dipende dal servizio e dal contesto. Per ulteriori informazioni, consulta Configurare le credenziali predefinite dell'applicazione.

Per un ambiente di sviluppo locale, puoi configurare ADC con le credenziali associati al tuo Account Google:

  1. After installing the Google Cloud CLI, configure the gcloud CLI to use your federated identity and then initialize it by running the following command:

    gcloud init
  2. Create local authentication credentials for your user account:

    gcloud auth application-default login

    If an authentication error is returned, confirm that you have configured the gcloud CLI to use Workforce Identity Federation.

    Viene visualizzata una schermata di accesso. Dopo aver eseguito l'accesso, le tue credenziali vengono memorizzate nella delle credenziali locali utilizzato da ADC.

Utilizzare la libreria client

L'esempio seguente mostra come utilizzare la libreria client.

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 {writeFile} = require('node:fs/promises');

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

  // Save the generated binary audio content to a local file
  await writeFile('output.mp3', response.audioContent, 'binary');
  console.log('Audio content written to file: output.mp3');
}

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

Risorse aggiuntive

C++

L'elenco seguente contiene link ad altre risorse correlate alla libreria client per C++:

C#

Il seguente elenco contiene link ad altre risorse correlate agli libreria client per C#:

Go

Il seguente elenco contiene link ad altre risorse correlate alla libreria client per Go:

Java

Il seguente elenco contiene link ad altre risorse correlate agli libreria client per Java:

Node.js

Il seguente elenco contiene link ad altre risorse correlate agli libreria client per Node.js:

PHP

Il seguente elenco contiene link ad altre risorse correlate agli libreria client per PHP:

Python

Il seguente elenco contiene link ad altre risorse correlate alla libreria client per Python:

Ruby

Il seguente elenco contiene link ad altre risorse correlate alla libreria client per Ruby: