Reproduce direcciones en voz alta con SSML

En este instructivo, se muestra cómo usar el lenguaje de marcación de síntesis de voz (SSML) para que se pronuncie un archivo de texto de direcciones. Puedes marcar una string de texto con etiquetas SSML a fin de personalizar el audio sintético de Text-to-Speech.

Texto sin formato Procesamiento SSML de texto sin formato

123 Street Ln

<speak>123 Street Ln</speak>

1 Number St

<speak>1 Number St</speak>

1 Piazza del Fibonacci

<speak>1 Piazza del Fibonacci</speak>

Objetivo

Envía una solicitud de voz sintética a Text-to-Speech con SSML y las bibliotecas cliente de Text-to-Speech.

Costos

Para obtener información sobre los costos, consulta la página de precios de Text-to-Speech.

Antes de comenzar

Descarga las muestras de código

Para descargar las muestras de código, clona las muestras de GitHub de Google Cloud correspondientes al lenguaje de programación que pretendes usar.

Java

En este instructivo, se usa código en el directorio texttospeech/cloud-client/src/main/java/com/example/texttospeech/ del repositorio de muestras de Java de Google Cloud Platform.

Para descargar y navegar hasta el código de este instructivo, ejecuta los siguientes comandos desde la terminal.

git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git
cd java-docs-samples/texttospeech/cloud-client/src/main/java/com/example/texttospeech/

Node.js

En este instructivo, se usa código en el directorio texttospeech del repositorio de muestras de Node.js de Google Cloud Platform.

Para descargar y navegar hasta el código de este instructivo, ejecuta los siguientes comandos desde la terminal.

git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git
cd texttospeech/

Python

En este instructivo, se usa código en el directorio texttospeech/snippets del repositorio de muestras de Python de Google Cloud Platform.

Para descargar y navegar hasta el código de este instructivo, ejecuta los siguientes comandos desde la terminal.

git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git
cd samples/snippets

Instala la biblioteca cliente

En este instructivo, se usa la biblioteca cliente de Text-to-Speech.

Java

En este instructivo, se usan las siguientes dependencias.

<!--  Using libraries-bom to manage versions.
See https://github.com/GoogleCloudPlatform/cloud-opensource-java/wiki/The-Google-Cloud-Platform-Libraries-BOM -->
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>26.32.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>

Node.js

Desde la terminal, ejecuta el siguiente comando.

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

Python

Desde la terminal, ejecuta el siguiente comando.

pip install --upgrade google-cloud-texttospeech

Configura tus credenciales de Google Cloud Platform

Configura la variable de entorno GOOGLE_APPLICATION_CREDENTIALS para proporcionar credenciales de autenticación al código de la aplicación. Esta variable solo se aplica a la sesión actual de shell. Si quieres que la variable se aplique a sesiones de shell futuras, configura la variable en tu archivo de inicio de shell, por ejemplo, en el archivo ~/.bashrc o ~/.profile.

Linux o macOS

export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Reemplaza KEY_PATH por la ruta del archivo JSON que contiene tus credenciales.

Por ejemplo:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"

Windows

Para PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Reemplaza KEY_PATH por la ruta del archivo JSON que contiene tus credenciales.

Por ejemplo:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"

Para el símbolo del sistema:

set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH

Reemplaza KEY_PATH por la ruta del archivo JSON que contiene tus credenciales.

Importa las bibliotecas

En este instructivo, se usan las siguientes bibliotecas cliente y del sistema.

Java

Para obtener información sobre cómo instalar y usar la biblioteca cliente de Text-to-Speech, consulta las bibliotecas cliente de Text-to-Speech. Para obtener más información, consulta la documentación de referencia de la API de Text-to-Speech Java.

Para autenticarte en Text-to-Speech, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

// 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.common.html.HtmlEscapers;
import com.google.protobuf.ByteString;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

Node.js

Para obtener información sobre cómo instalar y usar la biblioteca cliente de Text-to-Speech, consulta las bibliotecas cliente de Text-to-Speech. Para obtener más información, consulta la documentación de referencia de la API de Text-to-Speech Node.js.

Para autenticarte en Text-to-Speech, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

// Import other required libraries
const fs = require('fs');
//const escape = require('escape-html');
const util = require('util');

Python

Para obtener información sobre cómo instalar y usar la biblioteca cliente de Text-to-Speech, consulta las bibliotecas cliente de Text-to-Speech. Para obtener más información, consulta la documentación de referencia de la API de Text-to-Speech Python.

Para autenticarte en Text-to-Speech, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import html

from google.cloud import texttospeech

Usa la API de Text-to-Speech

La siguiente función toma una string de texto etiquetado con SSML y el nombre de un archivo MP3. En esta función, se usa el texto etiquetado con SSML para generar audio sintético. La función guarda el audio sintético con el nombre de archivo MP3 designado como parámetro.

Toda la entrada de SSML puede ser leída por una sola voz. Puedes configurar la voz en el objeto VoiceSelectionParams.

Java

Para obtener información sobre cómo instalar y usar la biblioteca cliente de Text-to-Speech, consulta las bibliotecas cliente de Text-to-Speech. Para obtener más información, consulta la documentación de referencia de la API de Text-to-Speech Java.

Para autenticarte en Text-to-Speech, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

/**
 * Generates synthetic audio from a String of SSML text.
 *
 * <p>Given a string of SSML text and an output file name, this function calls the Text-to-Speech
 * API. The API returns a synthetic audio version of the text, formatted according to the SSML
 * commands. This function saves the synthetic audio to the designated output file.
 *
 * @param ssmlText String of tagged SSML text
 * @param outFile String name of file under which to save audio output
 * @throws Exception on errors while closing the client
 */
public static void ssmlToAudio(String ssmlText, String outFile) throws Exception {
  // Instantiates a client
  try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) {
    // Set the ssml text input to synthesize
    SynthesisInput input = SynthesisInput.newBuilder().setSsml(ssmlText).build();

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

    // Select the audio file type
    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(outFile)) {
      out.write(audioContents.toByteArray());
      System.out.println("Audio content written to file " + outFile);
    }
  }
}

Node.js

Para obtener información sobre cómo instalar y usar la biblioteca cliente de Text-to-Speech, consulta las bibliotecas cliente de Text-to-Speech. Para obtener más información, consulta la documentación de referencia de la API de Text-to-Speech Node.js.

Para autenticarte en Text-to-Speech, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

/**
 * Generates synthetic audio from a String of SSML text.
 *
 * Given a string of SSML text and an output file name, this function
 * calls the Text-to-Speech API. The API returns a synthetic audio
 * version of the text, formatted according to the SSML commands. This
 * function saves the synthetic audio to the designated output file.
 *
 * ARGS
 * ssmlText: String of tagged SSML text
 * outfile: String name of file under which to save audio output
 * RETURNS
 * nothing
 *
 */
async function ssmlToAudio(ssmlText, outFile) {
  // Creates a client
  const client = new textToSpeech.TextToSpeechClient();

  // Constructs the request
  const request = {
    // Select the text to synthesize
    input: {ssml: ssmlText},
    // Select the language and SSML Voice Gender (optional)
    voice: {languageCode: 'en-US', ssmlGender: 'MALE'},
    // 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(outFile, response.audioContent, 'binary');
  console.log('Audio content written to file ' + outFile);
}

Python

Para obtener información sobre cómo instalar y usar la biblioteca cliente de Text-to-Speech, consulta las bibliotecas cliente de Text-to-Speech. Para obtener más información, consulta la documentación de referencia de la API de Text-to-Speech Python.

Para autenticarte en Text-to-Speech, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

def ssml_to_audio(ssml_text, outfile):
    # Generates SSML text from plaintext.
    #
    # Given a string of SSML text and an output file name, this function
    # calls the Text-to-Speech API. The API returns a synthetic audio
    # version of the text, formatted according to the SSML commands. This
    # function saves the synthetic audio to the designated output file.
    #
    # Args:
    # ssml_text: string of SSML text
    # outfile: string name of file under which to save audio output
    #
    # Returns:
    # nothing

    # Instantiates a client
    client = texttospeech.TextToSpeechClient()

    # Sets the text input to be synthesized
    synthesis_input = texttospeech.SynthesisInput(ssml=ssml_text)

    # Builds the voice request, selects the language code ("en-US") and
    # the SSML voice gender ("MALE")
    voice = texttospeech.VoiceSelectionParams(
        language_code="en-US", ssml_gender=texttospeech.SsmlVoiceGender.MALE
    )

    # Selects the type of audio file to return
    audio_config = texttospeech.AudioConfig(
        audio_encoding=texttospeech.AudioEncoding.MP3
    )

    # Performs 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
    )

    # Writes the synthetic audio to the output file.
    with open(outfile, "wb") as out:
        out.write(response.audio_content)
        print("Audio content written to file " + outfile)

Personaliza el audio sintético

Con la siguiente función, se toma el nombre de un archivo de texto y se convierte el contenido del archivo en una string de texto etiquetado con SSML.

Java

Para obtener información sobre cómo instalar y usar la biblioteca cliente de Text-to-Speech, consulta las bibliotecas cliente de Text-to-Speech. Para obtener más información, consulta la documentación de referencia de la API de Text-to-Speech Java.

Para autenticarte en Text-to-Speech, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

/**
 * Generates SSML text from plaintext.
 *
 * <p>Given an input filename, this function converts the contents of the input text file into a
 * String of tagged SSML text. This function formats the SSML String so that, when synthesized,
 * the synthetic audio will pause for two seconds between each line of the text file. This
 * function also handles special text characters which might interfere with SSML commands.
 *
 * @param inputFile String name of plaintext file
 * @return a String of SSML text based on plaintext input.
 * @throws IOException on files that don't exist
 */
public static String textToSsml(String inputFile) throws Exception {

  // Read lines of input file
  String rawLines = new String(Files.readAllBytes(Paths.get(inputFile)));

  // Replace special characters with HTML Ampersand Character Codes
  // These codes prevent the API from confusing text with SSML tags
  // For example, '<' --> '&lt;' and '&' --> '&amp;'
  String escapedLines = HtmlEscapers.htmlEscaper().escape(rawLines);

  // Convert plaintext to SSML
  // Tag SSML so that there is a 2 second pause between each address
  String expandedNewline = escapedLines.replaceAll("\\n", "\n<break time='2s'/>");
  String ssml = "<speak>" + expandedNewline + "</speak>";

  // Return the concatenated String of SSML
  return ssml;
}

Node.js

Para obtener información sobre cómo instalar y usar la biblioteca cliente de Text-to-Speech, consulta las bibliotecas cliente de Text-to-Speech. Para obtener más información, consulta la documentación de referencia de la API de Text-to-Speech Node.js.

Para autenticarte en Text-to-Speech, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

/**
 * Generates SSML text from plaintext.
 *
 * Given an input filename, this function converts the contents of the input text file
 * into a String of tagged SSML text. This function formats the SSML String so that,
 * when synthesized, the synthetic audio will pause for two seconds between each line
 * of the text file. This function also handles special text characters which might
 * interfere with SSML commands.
 *
 * ARGS
 * inputfile: String name of plaintext file
 * RETURNS
 * a String of SSML text based on plaintext input
 *
 */
function textToSsml(inputFile) {
  let rawLines = '';
  // Read input file
  try {
    rawLines = fs.readFileSync(inputFile, 'utf8');
  } catch (e) {
    console.log('Error:', e.stack);
    return;
  }

  // Replace special characters with HTML Ampersand Character Codes
  // These codes prevent the API from confusing text with SSML tags
  // For example, '<' --> '&lt;' and '&' --> '&amp;'
  let escapedLines = rawLines;
  escapedLines = escapedLines.replace(/&/g, '&amp;');
  escapedLines = escapedLines.replace(/"/g, '&quot;');
  escapedLines = escapedLines.replace(/</g, '&lt;');
  escapedLines = escapedLines.replace(/>/g, '&gt;');

  // Convert plaintext to SSML
  // Tag SSML so that there is a 2 second pause between each address
  const expandedNewline = escapedLines.replace(/\n/g, '\n<break time="2s"/>');
  const ssml = '<speak>' + expandedNewline + '</speak>';

  // Return the concatenated String of SSML
  return ssml;
}

Python

Para obtener información sobre cómo instalar y usar la biblioteca cliente de Text-to-Speech, consulta las bibliotecas cliente de Text-to-Speech. Para obtener más información, consulta la documentación de referencia de la API de Text-to-Speech Python.

Para autenticarte en Text-to-Speech, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

def text_to_ssml(inputfile):
    # Generates SSML text from plaintext.
    # Given an input filename, this function converts the contents of the text
    # file into a string of formatted SSML text. This function formats the SSML
    # string so that, when synthesized, the synthetic audio will pause for two
    # seconds between each line of the text file. This function also handles
    # special text characters which might interfere with SSML commands.
    #
    # Args:
    # inputfile: string name of plaintext file
    #
    # Returns:
    # A string of SSML text based on plaintext input

    # Parses lines of input file
    with open(inputfile) as f:
        raw_lines = f.read()

    # Replace special characters with HTML Ampersand Character Codes
    # These Codes prevent the API from confusing text with
    # SSML commands
    # For example, '<' --> '&lt;' and '&' --> '&amp;'

    escaped_lines = html.escape(raw_lines)

    # Convert plaintext to SSML
    # Wait two seconds between each address
    ssml = "<speak>{}</speak>".format(
        escaped_lines.replace("\n", '\n<break time="2s"/>')
    )

    # Return the concatenated string of ssml script
    return ssml

Combina todas las opciones

En este programa, se usa la siguiente entrada.

123 Street Ln, Small Town, IL 12345 USA
1 Jenny St & Number St, Tutone City, CA 86753
1 Piazza del Fibonacci, 12358 Pisa, Italy

Cuando se pasa el texto anterior a text_to_ssml(), se genera el siguiente texto etiquetado.

<speak>123 Street Ln, Small Town, IL 12345 USA
<break time="2s"/>1 Jenny St &amp; Number St, Tutone City, CA 86753
<break time="2s"/>1 Piazza del Fibonacci, 12358 Pisa, Italy
<break time="2s"/></speak>

Ejecuta el código

Para generar un archivo de audio de voz sintética, ejecuta el siguiente código desde la línea de comandos.

Java

Linux o MacOS

En el directorio java-docs-samples/texttospeech/cloud-client/, ejecuta el siguiente comando en la línea de comandos.

$ mvn clean package

Windows

En el directorio java-docs-samples/texttospeech/cloud-client/, ejecuta el siguiente comando en la línea de comandos.

$ mvn clean package

Node.js

Linux o MacOS

En el archivo hybridGlossaries.js, quita el comentario de las variables comentadas de TODO (developer).

En el siguiente comando, reemplaza projectId por el ID de tu proyecto de Google Cloud. En el directorio nodejs-docs-samples/texttospeech, ejecuta el siguiente comando en la línea de comandos.

$ node ssmlAddresses.js projectId

Windows

En el archivo hybridGlossaries.js, quita el comentario de las variables comentadas de TODO (developer).

En el siguiente comando, reemplaza projectId por el ID de tu proyecto de Google Cloud. En el directorio nodejs-docs-samples/texttospeech, ejecuta el siguiente comando en la línea de comandos.

$env: C:/Node.js/node.exe C: ssmlAddresses.js projectId

Python

Linux o MacOS

En el directorio python-docs-samples/texttospeech/snippets, ejecuta el siguiente comando en la línea de comandos.

$ python ssml_addresses.py

Windows

En el directorio python-docs-samples/texttospeech/snippets, ejecuta el siguiente comando en la línea de comandos.

$env: C:/Python3/python.exe C: ssml_addresses.py

Comprueba el resultado

Este programa genera un archivo de audio example.mp3 de voz sintética.

Java

Navega al directorio java-docs-samples/texttospeech/cloud-client/resources/.

Busca en el directorio resources el archivo example.mp3.

Node.js

Navega al directorio nodejs-docs-samples/texttospeech/resources/.

Busca en el directorio resources el archivo example.mp3.

Python

Navega hasta python-docs-samples/texttospeech/snippets/resources.

Busca en el directorio resources el archivo example.mp3.

Escucha el siguiente clip de audio para comprobar que tu archivo example.mp3 suene igual.


Solucionar problemas

  • Si olvidas establecer la variable de entorno GOOGLE_APPLICATION_CREDENTIALS en la línea de comandos, se generará el siguiente mensaje de error:

    The Application Default Credentials are not available.

  • Si pasas el nombre de un archivo que no existe a text_to_ssml(), se genera el siguiente mensaje de error:

    IOError: [Errno 2] No such file or directory
    

  • Pasar ssml_to_audio() un parámetro ssml_text que contenga None genera el siguiente mensaje de error:

    InvalidArgument: 400 Invalid input type. Type has to be text or SSML
    

  • Asegúrate de que estás ejecutando el código desde el directorio correcto.

¿Qué sigue?

Limpia

Para evitar que se apliquen cargos a tu cuenta de Google Cloud Platform por los recursos utilizados en este instructivo, usa la consola de Google Cloud para borrar tu proyecto si no lo necesitas.

Borra tu proyecto

  1. En la consola de Google Cloud, ve a la página Proyectos.
  2. En la lista de proyectos, selecciona el proyecto que deseas borrar y haz clic en Borrar.
  3. En el cuadro de diálogo, escribe el ID del proyecto y haz clic en Cerrar para borrar el proyecto.