Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Criar áudio do texto usando a linha de comando
Este documento explica o processo de fazer uma solicitação ao
Text-to-Speech usando a linha de comando. Para saber mais sobre os conceitos básicos
do Text-to-Speech, leia
Princípios básicos do Text-to-Speech.
Antes de começar
Antes de enviar uma solicitação para a API Text-to-Speech, é preciso concluir
as ações a seguir. Consulte a
página antes de começar para ver os detalhes.
Ativar o Text-to-Speech em um projeto do GCP.
Verificar se o faturamento está ativado para o Text-to-Speech.
Converta texto em áudio fazendo uma solicitação HTTP POST para o endpoint
https://texttospeech.googleapis.com/v1/text:synthesize. No
corpo do seu comando POST, especifique o tipo de voz que será sintetizado na
seção de configuração voice. Especifique também o texto que será sintetizado no
campo text da seção input e, por fim, especifique o tipo de áudio que será criado
na seção audioConfig.
Execute a solicitação REST abaixo na linha de comando para sintetizar o áudio do texto usando o Text-to-Speech. O comando usa o comando gcloud auth
application-default print-access-token para recuperar um token de autorização da solicitação.
Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:
PROJECT_ID: o ID alfanumérico do seu projeto do Google Cloud.
Método HTTP e URL:
POST https://texttospeech.googleapis.com/v1/text:synthesize
Corpo JSON da solicitação:
{
"input": {
"text": "Android is a mobile operating system developed by Google, based on the Linux kernel and designed primarily for touchscreen mobile devices such as smartphones and tablets."
},
"voice": {
"languageCode": "en-gb",
"name": "en-GB-Standard-A",
"ssmlGender": "FEMALE"
},
"audioConfig": {
"audioEncoding": "MP3"
}
}
Para enviar a solicitação, expanda uma destas opções:
curl (Linux, macOS ou Cloud Shell)
Salve o corpo da solicitação em um arquivo com o nome request.json e execute o comando a seguir:
A saída JSON para o comando REST contém o áudio sintetizado no formato de codificação em base64. Copie o conteúdo do campo audioContent para um novo arquivo chamado synthesize-output-base64.txt. O novo arquivo terá uma aparência semelhante à seguinte:
Decodifique o conteúdo do arquivo synthesize-output-base64.txt em um novo arquivo chamado synthesized-audio.mp3. Para informações
sobre a decodificação de base64, consulte Como decodificar conteúdo de áudio codificado em Base64.
Linux
Copie apenas o conteúdo codificado em base64 para um arquivo de texto.
Decodifique o arquivo de texto de origem usando a ferramenta de linha de comando
base64 usando a sinalização -d:
Reproduza o conteúdo de synthesized-audio.mp3 em um aplicativo de áudio ou em um
dispositivo de áudio. Também é possível abrir o synthesized-audio.mp3 no navegador Chrome
para reproduzir o áudio, navegando até a pasta que contém
o arquivo, por exemplo, file://my_file_path/synthesized-audio.mp3
Limpar
Para evitar cobranças desnecessárias do Google Cloud Platform, use o console do Google Cloud para excluir o projeto se ele não for mais necessário.
A seguir
Saiba mais sobre a Cloud Text-to-Speech lendo as noções básicas.
Verifique a lista de vozes disponíveis que você pode usar para fala sintética.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-08-18 UTC."],[],[],null,["# Quickstart: Create audio from text by using the command line\n\nCreate audio from text by using the command line\n================================================\n\nThis document walks you through the process of making a request to\nText-to-Speech using the command line. To learn more about the fundamental\nconcepts in Text-to-Speech, read\n[Text-to-Speech Basics](/text-to-speech/docs/basics).\n\nBefore you begin\n----------------\n\nBefore you can send a request to the Text-to-Speech API, you must have completed\nthe following actions. See the\n[before you begin](/text-to-speech/docs/before-you-begin) page for details.\n\n- Enable Text-to-Speech on a GCP project.\n- Make sure billing is enabled for Text-to-Speech.\n-\n [Install](/sdk/docs/install) the Google Cloud CLI, and then\n [sign in to the gcloud CLI with your federated identity](/iam/docs/workforce-log-in-gcloud).\n\n After signing in,\n [initialize](/sdk/docs/initializing) the Google Cloud CLI by running the following command:\n\n ```bash\n gcloud init\n ```\n\nSynthesize audio from text\n--------------------------\n\nYou can convert text to audio by making an HTTP POST request to the\n`https://texttospeech.googleapis.com/v1/text:synthesize` endpoint. In\nthe body of your POST command, specify the type of voice to synthesize in\nthe `voice` configuration section, specify the text to synthesize in the\n`text` field of the `input` section, and specify the type of audio to create\nin the `audioConfig` section.\n\n1. Execute the REST request below at the command line to synthesize audio from\n text using Text-to-Speech. The command uses the `gcloud auth\n application-default print-access-token` command to retrieve an authorization\n token for the request.\n\n\n Before using any of the request data,\n make the following replacements:\n - \u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e: the alphanumeric ID of your Google Cloud project.\n\n\n HTTP method and URL:\n\n ```\n POST https://texttospeech.googleapis.com/v1/text:synthesize\n ```\n\n\n Request JSON body:\n\n ```\n {\n \"input\": {\n \"text\": \"Android is a mobile operating system developed by Google, based on the Linux kernel and designed primarily for touchscreen mobile devices such as smartphones and tablets.\"\n },\n \"voice\": {\n \"languageCode\": \"en-gb\",\n \"name\": \"en-GB-Standard-A\",\n \"ssmlGender\": \"FEMALE\"\n },\n \"audioConfig\": {\n \"audioEncoding\": \"MP3\"\n }\n }\n ```\n\n To send your request, expand one of these options:\n\n #### curl (Linux, macOS, or Cloud Shell)\n\n | **Note:** The following command assumes that you have logged in to the `gcloud` CLI with your user account by running [`gcloud init`](/sdk/gcloud/reference/init) or [`gcloud auth login`](/sdk/gcloud/reference/auth/login) , or by using [Cloud Shell](/shell/docs), which automatically logs you into the `gcloud` CLI . You can check the currently active account by running [`gcloud auth list`](/sdk/gcloud/reference/auth/list).\n\n\n Save the request body in a file named `request.json`,\n and execute the following command:\n\n ```\n curl -X POST \\\n -H \"Authorization: Bearer $(gcloud auth print-access-token)\" \\\n -H \"x-goog-user-project: PROJECT_ID\" \\\n -H \"Content-Type: application/json; charset=utf-8\" \\\n -d @request.json \\\n \"https://texttospeech.googleapis.com/v1/text:synthesize\"\n ```\n\n #### PowerShell (Windows)\n\n | **Note:** The following command assumes that you have logged in to the `gcloud` CLI with your user account by running [`gcloud init`](/sdk/gcloud/reference/init) or [`gcloud auth login`](/sdk/gcloud/reference/auth/login) . You can check the currently active account by running [`gcloud auth list`](/sdk/gcloud/reference/auth/list).\n\n\n Save the request body in a file named `request.json`,\n and execute the following command:\n\n ```\n $cred = gcloud auth print-access-token\n $headers = @{ \"Authorization\" = \"Bearer $cred\"; \"x-goog-user-project\" = \"PROJECT_ID\" }\n\n Invoke-WebRequest `\n -Method POST `\n -Headers $headers `\n -ContentType: \"application/json; charset=utf-8\" `\n -InFile request.json `\n -Uri \"https://texttospeech.googleapis.com/v1/text:synthesize\" | Select-Object -Expand Content\n ```\n\n You should receive a JSON response similar to the following:\n\n ```\n {\n \"audioContent\": \"//NExAASCCIIAAhEAGAAEMW4kAYPnwwIKw/BBTpwTvB+IAxIfghUfW..\"\n }\n ```\n\n \u003cbr /\u003e\n\n2. The JSON output for the REST command contains the synthesized audio in\n base64-encoded format. Copy the contents of the `audioContent` field into\n a new file named `synthesize-output-base64.txt`. Your new file will look something\n like the following:\n\n ```\n //NExAARqoIIAAhEuWAAAGNmBGMY4EBcxvABAXBPmPIAF//yAuh9Tn5CEap3/o\n ...\n VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n ```\n3. Decode the contents of the `synthesize-output-base64.txt` file into a new file\n named `synthesized-audio.mp3`. For information\n on decoding base64, see [Decoding Base64-Encoded Audio Content](/text-to-speech/docs/base64-decoding).\n\n ### Linux\n\n 1. Copy only the base-64 encoded content into a text file.\n\n 2. Decode the source text file using the base64 command line tool\n by using the `-d` flag:\n\n ```bash\n $ base64 SOURCE_BASE64_TEXT_FILE -d \u003e DESTINATION_AUDIO_FILE\n ```\n\n ### Mac OSX\n\n 1. Copy only the base-64 encoded content into a text file.\n\n 2. Decode the source text file using the base64 command line tool:\n\n ```bash\n $ base64 --decode SOURCE_BASE64_TEXT_FILE \u003e DESTINATION_AUDIO_FILE\n ```\n\n ### Windows\n\n 1. Copy only the base-64 encoded content into a text file.\n\n 2. Decode the source text file using the\n [`certutil`](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/certutil) command.\n\n ```bash\n certutil -decode SOURCE_BASE64_TEXT_FILE DESTINATION_AUDIO_FILE\n ```\n4. Play the contents of `synthesized-audio.mp3` in an audio application or on\n an audio device. You can also open the `synthesized-audio.mp3` in the Chrome\n browser to play the audio by navigating to the folder that contains\n the file, for example `file://my_file_path/synthesized-audio.mp3`\n\nClean up\n--------\n\nTo avoid unnecessary Google Cloud Platform charges, use the\n[Google Cloud console](https://console.cloud.google.com/) to delete your project if you do not need it.\n\nWhat's next\n-----------\n\n\n- Learn more about Cloud Text-to-Speech by reading the [basics](/text-to-speech/docs/basics).\n- Review the list of [available voices](/text-to-speech/docs/voices) you can use for synthetic speech.\n\n\u003cbr /\u003e"]]