Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Você pode enviar dados de áudio para a API Speech-to-Text diretamente (no campo
content
da solicitação) ou fazer com que a API execute o reconhecimento remoto em dados armazenados em um
bucket do Cloud Storage. Para isso, especifique o objeto de armazenamento no campo uri
da solicitação.
Todos os dados de áudio no campo content em solicitações HTTP precisam estar no formato Base64.
Nesta página, veja como converter áudio de um arquivo binário para dados codificados como Base64.
Como usar a linha de comando
Em uma solicitação gRPC, é possível simplesmente gravar os dados binários diretamente.
No entanto, JSON é usado ao fazer uma solicitação REST. JSON
é um formato de texto que não suporta diretamente dados binários, então você precisará
converter esses dados binários em texto usando a
codificação Base64.
A maioria dos ambientes de desenvolvimento contém um utilitário base64 nativo para
codificar um binário em dados de texto ASCII. Para codificar um arquivo:
Linux
Codifique o arquivo de áudio usando a ferramenta de linha de comando base64, evitando a quebra
automática de linha usando a flag -w 0:
base64 INPUT_FILE -w 0 > OUTPUT_FILE
macOS
Codifique o arquivo usando a ferramenta de linha de comando do base64:
base64 -i INPUT_FILE -o OUTPUT_FILE
Windows
Codifique o arquivo usando a ferramenta Base64.exe:
Base64.exe -e INPUT_FILE > OUTPUT_FILE
PowerShell
Codifique o arquivo usando o método Convert.ToBase64String:
Incorporar dados binários de áudio em solicitações por meio de editores de texto não é desejável,
nem prático. Na prática, você estará incorporando arquivos com codificação Base64 no
código do cliente. Todas as linguagens de programação compatíveis têm mecanismos integrados
para o conteúdo de codificação Base64:
Python
Em Python, codifique os arquivos de áudio em base64 da seguinte maneira:
# Import the base64 encoding library.importbase64# Pass the audio data to an encoding function.defencode_audio(audio_file):withopen(audio_file,"rb")asf:encoded_content=base64.b64encode(f.read())returnencoded_content
Node.js
// Read the file into memory.varfs=require('fs');varaudioFile=fs.readFileSync('/full/path/to/audio/file.wav');// Convert the audio data to a Buffer and base64 encode it.varencoded=Buffer.from(audioFile).toString('base64');
Java
// Import the Base64 encoding library.importorg.apache.commons.codec.binary.Base64;// Encode the audio.byte[]audioData=Base64.encodeBase64(audioFile.getBytes());StringencodedString=Base64.getEncoder().encodeToString(audioData);
Go
import("bufio""encoding/base64""io""os")// Open audio file.f,_:=os.Open("/full/path/to/audio/file.wav")// Read entire audio into byte slice.reader:=bufio.NewReader(f)content,_:=io.ReadAll(reader)// Encode audio as base64.base64.StdEncoding.EncodeToString(content)
[[["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-29 UTC."],[],[],null,["# Base64 encoding audio content\n\nWhen you send audio data to the Speech-to-Text API, you can either send the\ndata directly (within the request's\n[`content`](/speech-to-text/v2/docs/reference/rpc/google.cloud.speech.v2#google.cloud.speech.v2.RecognizeRequest.FIELDS.bytes.google.cloud.speech.v2.RecognizeRequest.content)\nfield) or have the API perform recognition remotely on data stored in a\nCloud Storage bucket by specifying the storage object in the request's\n[`uri`](/speech-to-text/v2/docs/reference/rpc/google.cloud.speech.v2#google.cloud.speech.v2.RecognizeRequest.FIELDS.string.google.cloud.speech.v2.RecognizeRequest.uri)\nfield.\n\nAny audio data in the `content` field in HTTP requests must be in base64 format.\nThis page describes how to convert audio from a binary file to base64-encoded data.\n| **Note:** For clients using client libraries or a gRPC client, audio content should be in binary format, not base64 format.\n| **Note:** Check the [quotas and limits](/speech-to-text/v2/quotas) documentation for the content limits on inline audio.\n\nUsing the command line\n----------------------\n\nWithin a gRPC request, you can simply write binary data out directly;\nhowever, JSON is used when making a REST request. JSON\nis a text format that does not directly support binary data, so you will need to\nconvert such binary data into text using\n[Base64](https://en.wikipedia.org/wiki/Base64) encoding.\n\nMost development environments contain a native `base64` utility to\nencode a binary into ASCII text data. To encode a file: \n\n### Linux\n\nEncode the file using the `base64` command line tool, making sure to\nprevent line-wrapping by using the `-w 0` flag: \n\n```\nbase64 INPUT_FILE -w 0 \u003e OUTPUT_FILE\n```\n\n### macOS\n\nEncode the file using the `base64` command line tool: \n\n```\nbase64 -i INPUT_FILE -o OUTPUT_FILE\n```\n\n### Windows\n\nEncode the file using the `Base64.exe` tool: \n\n```\nBase64.exe -e INPUT_FILE \u003e OUTPUT_FILE\n```\n\n### PowerShell\n\nEncode the file using the `Convert.ToBase64String` method: \n\n```\n[Convert]::ToBase64String([IO.File]::ReadAllBytes(\"./INPUT_FILE\")) \u003e OUTPUT_FILE\n```\n\nCreate a JSON request file, inlining the base64-encoded data: \n\n### JSON\n\n\n {\n \"recognizer\": \"projects/\u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e/locations/global/recognizers/_\",\n \"content\": \"ZkxhQwAAACIQABAAAAUJABtAA+gA8AB+W8FZndQvQAyjv...\"\n }\n\n\u003cbr /\u003e\n\nUsing client libraries\n----------------------\n\nEmbedding binary data into requests through text editors is neither\ndesirable or practical. In practice, you will be embedding base64 encoded files\nwithin client code. All supported programming languages have built-in mechanisms\nfor base64 encoding content.\n\n\n### Python\n\nIn Python, base64 encode audio files as follows: \n\n # Import the base64 encoding library.\n import base64\n\n # Pass the audio data to an encoding function.\n def encode_audio(audio_file):\n with open(audio_file, \"rb\") as f:\n encoded_content = base64.b64encode(f.read())\n return encoded_content\n\n### Node.js\n\n // Read the file into memory.\n var fs = require('fs');\n var audioFile = fs.readFileSync('\u003cvar translate=\"no\"\u003e/full/path/to/audio/file.wav\u003c/var\u003e');\n\n // Convert the audio data to a Buffer and base64 encode it.\n var encoded = Buffer.from(audioFile).toString('base64');\n\n### Java\n\n // Import the Base64 encoding library.\n import org.apache.commons.codec.binary.Base64;\n\n // Encode the audio.\n byte[] audioData = Base64.encodeBase64(audioFile.getBytes());\n String encodedString = Base64.getEncoder().encodeToString(audioData);\n\n### Go\n\n import (\n \"bufio\"\n \"encoding/base64\"\n \"io\"\n \"os\"\n )\n\n // Open audio file.\n f, _ := os.Open(\"\u003cvar translate=\"no\"\u003e/full/path/to/audio/file.wav\u003c/var\u003e\")\n\n // Read entire audio into byte slice.\n reader := bufio.NewReader(f)\n content, _ := io.ReadAll(reader)\n\n // Encode audio as base64.\n base64.StdEncoding.EncodeToString(content)\n\n\u003cbr /\u003e"]]