使用 API 將語音轉錄為文字
此頁面說明如何使用 REST 介面和 curl
指令,將語音辨識要求傳送至語音轉文字。
Speech-to-Text 可讓您將 Google 語音辨識技術輕鬆整合至開發人員應用程式。您可將音訊資料傳送至 Speech-to-Text API,然後 API 會傳回該音訊檔案的文字轉錄結果。如要進一步瞭解這項服務,請參閱語音轉文字基本資訊。
事前準備
您必須先完成下列操作,才能向 Speech-to-Text API 傳送要求。詳情請參閱「事前準備」頁面。
- 在 GCP 專案中啟用 Speech-to-Text。
- 請確認已為 Speech-to-Text 啟用計費功能。
-
After installing the Google Cloud CLI, initialize it by running the following command:
gcloud init
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
- (選用) 建立新的 Google Cloud Storage 值區,用於儲存音訊資料。
提出音訊轉錄要求
現在您可以使用 Speech-to-Text 將音訊檔案轉錄成文字。請使用下列程式碼範例,將 recognize
REST 要求傳送至 Speech-to-Text API。
-
建立具有下列文字的 JSON 要求檔案,並儲存為
sync-request.json
純文字檔案:{ "config": { "encoding":"FLAC", "sampleRateHertz": 16000, "languageCode": "en-US", "enableWordTimeOffsets": false }, "audio": { "uri":"gs://cloud-samples-tests/speech/brooklyn.flac" } }
這個 JSON 程式碼片段表示音訊檔案採用 FLAC 編碼格式、取樣率為 16000 Hz,且音訊檔案儲存在 Google Cloud Storage 中,並提供指定的 URI。音訊檔案可供公眾存取,因此您不需要驗證憑證即可存取檔案。
-
使用
curl
發出speech:recognize
要求,並傳遞您在步驟 1 中設定的 JSON 要求檔案名稱:範例
curl
指令使用gcloud auth print-access-token
指令取得驗證權杖。curl -s -H "Content-Type: application/json" \ -H "Authorization: Bearer "$(gcloud auth print-access-token) \ https://speech.googleapis.com/v1/speech:recognize \ -d @sync-request.json
請注意,如要將檔案名稱傳送給
curl
,請使用-d
選項 (針對「資料」),並在檔案名稱前加上@
符號。這個檔案的所在目錄應與您執行curl
指令的所在目錄相同。畫面會顯示類似以下的回應:
{ "results": [ { "alternatives": [ { "transcript": "how old is the Brooklyn Bridge", "confidence": 0.98267895 } ] } ] }
恭喜!您已將您的第一個要求傳送至 Speech-to-Text。
清除所用資源
如要避免系統向您的 Google Cloud 帳戶收取您在本頁所用資源的費用,請按照下列步驟操作。
- 如要刪除不需要的專案,請使用 Google Cloud console 。
後續步驟
- 練習轉錄短音訊檔案。
- 瞭解如何將長音訊檔案批次處理,以便進行語音辨識。
- 瞭解如何轉錄串流音訊,例如從麥克風轉錄。
- 使用 Speech-to-Text 用戶端程式庫,以您選擇的語言開始使用 Speech-to-Text。
- 逐步演練應用程式範例。
- 如要獲得最佳效能、準確率與其他提示,請參閱最佳做法說明文件。