Fale moradas com SSML

Este tutorial demonstra como usar a linguagem de marcação de síntese de voz (SSML) para falar um ficheiro de texto de moradas. Pode marcar uma string de texto com etiquetas SSML para personalizar o áudio sintético da conversão de texto em voz.

Texto simples Renderização de texto simples em SSML
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

Envie um pedido de voz sintética para a API Text-to-Speech através de SSML e das bibliotecas cliente da API Text-to-Speech.

Custos

Consulte a página de preços da funcionalidade de conversão de texto em voz para ver informações sobre custos.

Antes de começar

Transfira os exemplos de código

Para transferir os exemplos de código, clone os Google Cloud exemplos do GitHub para o linguagem de programação que pretende usar.

Java

Este tutorial usa código no diretório texttospeech/cloud-client/src/main/java/com/example/texttospeech/ do repositório de exemplos Java da Google Cloud Platform.

Para transferir e navegar para o código deste tutorial, execute os seguintes comandos a partir do 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

Este tutorial usa código no diretório texttospeech do repositório de exemplos do Node.js da Google Cloud Platform.

Para transferir e navegar para o código deste tutorial, execute os seguintes comandos a partir do terminal.

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

Python

Este tutorial usa código no diretório texttospeech/snippets do repositório de exemplos de Python da Google Cloud Platform.

Para transferir e navegar para o código deste tutorial, execute os seguintes comandos a partir do terminal.

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

Instale a biblioteca de cliente

Este tutorial usa a biblioteca cliente de conversão de texto em voz.

Java

Este tutorial usa as seguintes dependências.

<!--  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

No terminal, execute o seguinte comando.

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

Python

No terminal, execute o seguinte comando.

pip install --upgrade google-cloud-texttospeech

Configure as suas credenciais da Google Cloud Platform

Provide authentication credentials to your application code by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS. This variable applies only to your current shell session. If you want the variable to apply to future shell sessions, set the variable in your shell startup file, for example in the ~/.bashrc or ~/.profile file.

Linux ou macOS

export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Replace KEY_PATH with the path of the JSON file that contains your credentials.

For example:

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

Windows

For PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Replace KEY_PATH with the path of the JSON file that contains your credentials.

For example:

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

For command prompt:

set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH

Replace KEY_PATH with the path of the JSON file that contains your credentials.

Importe bibliotecas

Este tutorial usa as seguintes bibliotecas de sistema e de cliente.

Java

Para saber como instalar e usar a biblioteca cliente para a API Text-to-Speech, consulte o artigo Bibliotecas cliente da API Text-to-Speech. Para mais informações, consulte a documentação de referência da API JavaText-to-Speech.

Para se autenticar na API Text-to-Speech, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento 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 saber como instalar e usar a biblioteca cliente para a API Text-to-Speech, consulte o artigo Bibliotecas cliente da API Text-to-Speech. Para mais informações, consulte a documentação de referência da API Node.jsText-to-Speech.

Para se autenticar na API Text-to-Speech, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento 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 saber como instalar e usar a biblioteca cliente para a API Text-to-Speech, consulte o artigo Bibliotecas cliente da API Text-to-Speech. Para mais informações, consulte a documentação de referência da API PythonText-to-Speech.

Para se autenticar na API Text-to-Speech, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

import html

from google.cloud import texttospeech

Use a API Text-to-Speech

A função seguinte usa uma string de texto etiquetada com SSML e o nome de um ficheiro MP3. A função usa o texto etiquetado com SSML para gerar áudio sintético. A função guarda o áudio sintético no nome do ficheiro MP3 designado como um parâmetro.

Toda a entrada SSML só pode ser lida por uma única voz. Pode definir a voz no objeto VoiceSelectionParams.

Java

Para saber como instalar e usar a biblioteca cliente para a API Text-to-Speech, consulte o artigo Bibliotecas cliente da API Text-to-Speech. Para mais informações, consulte a documentação de referência da API JavaText-to-Speech.

Para se autenticar na API Text-to-Speech, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento 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 saber como instalar e usar a biblioteca cliente para a API Text-to-Speech, consulte o artigo Bibliotecas cliente da API Text-to-Speech. Para mais informações, consulte a documentação de referência da API Node.jsText-to-Speech.

Para se autenticar na API Text-to-Speech, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento 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 saber como instalar e usar a biblioteca cliente para a API Text-to-Speech, consulte o artigo Bibliotecas cliente da API Text-to-Speech. Para mais informações, consulte a documentação de referência da API PythonText-to-Speech.

Para se autenticar na API Text-to-Speech, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

def ssml_to_audio(ssml_text: str) -> None:
    """
    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
    """

    # 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("test_example.mp3", "wb") as out:
        out.write(response.audio_content)
        print("Audio content written to file " + "test_example.mp3")

Personalize o áudio sintético

A função seguinte recebe o nome de um ficheiro de texto e converte o conteúdo do ficheiro numa string de texto etiquetada com SSML.

Java

Para saber como instalar e usar a biblioteca cliente para a API Text-to-Speech, consulte o artigo Bibliotecas cliente da API Text-to-Speech. Para mais informações, consulte a documentação de referência da API JavaText-to-Speech.

Para se autenticar na API Text-to-Speech, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento 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 saber como instalar e usar a biblioteca cliente para a API Text-to-Speech, consulte o artigo Bibliotecas cliente da API Text-to-Speech. Para mais informações, consulte a documentação de referência da API Node.jsText-to-Speech.

Para se autenticar na API Text-to-Speech, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento 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 saber como instalar e usar a biblioteca cliente para a API Text-to-Speech, consulte o artigo Bibliotecas cliente da API Text-to-Speech. Para mais informações, consulte a documentação de referência da API PythonText-to-Speech.

Para se autenticar na API Text-to-Speech, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para um ambiente de desenvolvimento local.

def text_to_ssml(inputfile: str) -> str:
    """
    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: name of plaintext file
    Returns: 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

Combine tudo

Este programa usa a seguinte 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

A transmissão do texto acima para text_to_ssml() gera o seguinte 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>

Executar o código

Para gerar um ficheiro de áudio de voz sintética, execute o seguinte código a partir da linha de comandos.

Java

Linux ou MacOS

No diretório java-docs-samples/texttospeech/cloud-client/, execute o seguinte comando na linha de comandos.

$ mvn clean package

Windows

No diretório java-docs-samples/texttospeech/cloud-client/, execute o seguinte comando na linha de comandos.

$ mvn clean package

Node.js

Linux ou MacOS

No ficheiro hybridGlossaries.js, remova o comentário das variáveis TODO (developer).

No comando seguinte, substitua projectId pelo ID do seu Google Cloud projeto. No diretório nodejs-docs-samples/texttospeech, execute o seguinte comando na linha de comandos.

$ node ssmlAddresses.js projectId

Windows

No ficheiro hybridGlossaries.js, remova o comentário das variáveis TODO (developer).

No comando seguinte, substitua projectId pelo ID do seu Google Cloud projeto. No diretório nodejs-docs-samples/texttospeech, execute o seguinte comando na linha de comandos.

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

Python

Linux ou MacOS

No diretório python-docs-samples/texttospeech/snippets, execute o seguinte comando na linha de comandos.

$ python ssml_addresses.py

Windows

No diretório python-docs-samples/texttospeech/snippets, execute o seguinte comando na linha de comandos.

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

Verifique o resultado

Este programa gera um ficheiro de áudio example.mp3 de voz sintética.

Java

Navegue para o diretório java-docs-samples/texttospeech/cloud-client/resources/.

Verifique se existe um ficheiro example.mp3 no diretório resources.

Node.js

Navegue para o diretório nodejs-docs-samples/texttospeech/resources/.

Verifique se existe um ficheiro example.mp3 no diretório resources.

Python

Navegar para python-docs-samples/texttospeech/snippets/resources.

Verifique se existe um ficheiro example.mp3 no diretório resources.

Ouça o seguinte clipe de áudio para verificar se o ficheiro example.mp3 tem o mesmo som.


Resolver problemas

  • Se se esquecer de definir a variável de ambiente GOOGLE_APPLICATION_CREDENTIALS na linha de comandos, é gerada a seguinte mensagem de erro:

    The Application Default Credentials are not available.

  • A transmissão de text_to_ssml() o nome de um ficheiro inexistente gera a mensagem de erro:

    IOError: [Errno 2] No such file or directory
    

  • A transmissão de ssml_to_audio() a um parâmetro ssml_text que contém None gera a mensagem de erro:

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

  • Certifique-se de que está a executar o código a partir do diretório correto.

O que se segue?

Limpar

Para evitar incorrer em custos na sua conta da Google Cloud Platform pelos recursos usados neste tutorial, use a Google Cloud consola para eliminar o seu projeto, se não precisar dele.

Elimine o projeto

  1. Na Google Cloud consola, aceda à página Projetos.
  2. Na lista de projetos, selecione o projeto que quer eliminar e clique em Eliminar.
  3. Na caixa de diálogo, escreva o ID do projeto e clique em Encerrar para eliminar o projeto.