Base64 編碼音訊內容

將音訊資料傳送至 Speech-to-Text API 時,您可以直接傳送資料 (在要求的 content 欄位中),也可以讓 API 對儲存在 Cloud Storage 值區中的資料進行遠端辨識。如果音訊資料最多為 60 秒和 10 MB,您可以直接在 content 欄位中傳送資料,僅限同步辨識content 欄位中的任何音訊資料都必須採用 Base64 格式。本頁面說明如何將音訊從二進位檔案轉換為 Base64 編碼資料。

如果音訊資料超過 60 秒或 10 MB,必須儲存在 Cloud Storage 值區中,才能傳送給辨識服務。您可以非同步分析,而無需將其轉換為 base64 格式。詳情請參閱非同步辨識說明文件

使用指令列

在 gRPC 要求內,您只需直接寫出二進位資料即可;但是,當提出 REST 要求時,會使用 JSON。JSON 是一種文字格式,不直接支援二進位資料,因此您需要使用 Base64 編碼,將這類二進位資料轉換為文字。

大多數開發環境都包含原生 base64 公用程式,可將二進位資料編碼為 ASCII 文字資料。如要編碼檔案,請按照下列步驟操作:

Linux

使用 base64 指令列工具對檔案進行編碼,並使用 -w 0 標記確保不會換行:

base64 INPUT_FILE -w 0 > OUTPUT_FILE

macOS

使用 base64 指令列工具編碼檔案:

base64 -i INPUT_FILE -o OUTPUT_FILE

Windows

使用 Base64.exe 工具對檔案進行編碼:

Base64.exe -e INPUT_FILE > OUTPUT_FILE

PowerShell

使用 Convert.ToBase64String 方法對檔案進行編碼:

[Convert]::ToBase64String([IO.File]::ReadAllBytes("./INPUT_FILE")) > OUTPUT_FILE

建立 JSON 要求檔案,並內嵌 base64 編碼資料:

JSON

{
  "config": {
    "encoding": "FLAC",
    "sampleRateHertz": 16000,
    "languageCode": "en-US"
  },
  "audio": {
    "content": "ZkxhQwAAACIQABAAAAUJABtAA+gA8AB+W8FZndQvQAyjv..."
  }
}

使用用戶端程式庫

透過文字編輯器將二進位資料嵌入要求中,既不理想也不實際。實際上,您會將 base64 編碼的檔案嵌入用戶端程式碼內。所有支援的程式設計語言都擁有適用於 base64 編碼內容的內建機制。

Python

在 Python 中,會以下列方式對音訊檔案進行 base64 編碼:

# Import the base64 encoding library.
import base64

# Pass the audio data to an encoding function.
def encode_audio(audio):
  audio_content = audio.read()
  return base64.b64encode(audio_content)

Node.js

在 Node.js 中,base64 會以下列方式對音訊檔案進行編碼,其中 audioFile 是音訊編碼檔案的路徑。

const fs = require('fs');
const content = fs.readFileSync(audioFile).toString('base64');

Java

在 Java 中,請使用 org.apache.commons.codec.binary.Base64 中的 encodeBase64 靜態方法,對二進位檔案進行 base64 編碼:

// Import the Base64 encoding library.
import org.apache.commons.codec.binary.Base64;

// Encode the speech.
byte[] encodedAudio = Base64.encodeBase64(audio.getBytes());