將長音訊檔案轉錄成文字

這個頁面說明如何使用 Speech-to-Text API 和非同步語音辨識,將長音訊檔案 (長度超過 1 分鐘) 轉錄為文字。

關於非同步語音辨識

「非同步語音辨識」會啟動長時間執行的音訊處理作業。使用非同步語音辨識可轉錄長度超過 60 秒的音訊。如果是較短的音訊,使用同步語音辨識會更快、更簡單。非同步語音辨識的上限為 480 分鐘。

Speech-to-Text 和非同步處理

您可以將音訊內容從本機檔案直接傳送至 Speech-to-Text,以便非同步處理。不過,本機檔案的音訊時間限制為 60 秒。如果嘗試轉錄長度超過 60 秒的本機音訊檔案,系統會傳回錯誤。如要使用非同步語音辨識功能轉錄超過 60 秒的音訊,您必須將資料儲存在 Google Cloud Storage 值區中。

您可以使用 google.longrunning.Operations 方法擷取作業結果。結果會保留 5 天 (120 小時),方便您隨時取回。您也可以選擇直接將結果上傳至 Google Cloud Storage 值區。

使用 Google Cloud Storage 檔案轉錄長音訊檔案

這些範例會使用 Cloud Storage 值區來儲存長時間執行的轉錄程序所需的原始音訊輸入內容。如需一般 longrunningrecognize 作業回應的範例,請參閱參考文件

通訊協定

如要瞭解完整的詳細資訊,請參閱 speech:longrunningrecognize API 端點。

如要執行同步語音辨識,請提出 POST 要求並提供適當的要求主體。以下為使用 curlPOST 要求範例。這個範例使用 Google Cloud CLI 產生存取權杖。如需 gcloud CLI 安裝操作說明,請參閱快速入門

curl -X POST \
     -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
     -H "Content-Type: application/json; charset=utf-8" \
     --data "{
  'config': {
    'language_code': 'en-US'
  },
  'audio':{
    'uri':'gs://cloud-samples-tests/speech/brooklyn.flac'
  }
}" "https://speech.googleapis.com/v1/speech:longrunningrecognize"

如要進一步瞭解如何設定要求內容,請參閱 RecognitionConfigRecognitionAudio 參考說明文件。

如果要求成功,伺服器會傳回 200 OK HTTP 狀態碼與 JSON 格式的回應:

{
  "name": "7612202767953098924"
}

其中 name 是為要求建立的長時間執行作業名稱。

等待處理作業完成。處理時間長短會因來源音訊而異。在大多數情況下,您會獲得與來源音訊長度一半的結果。您可以向 https://speech.googleapis.com/v1/operations/ 端點提出 GET 要求,取得長時間執行作業的狀態。將 your-operation-name 替換為 longrunningrecognize 要求傳回的 name

curl -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
     -H "Content-Type: application/json; charset=utf-8" \
     "https://speech.googleapis.com/v1/operations/your-operation-name"

如果要求成功,伺服器會傳回 200 OK HTTP 狀態碼與 JSON 格式的回應:

{
  "name": "7612202767953098924",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.speech.v1.LongRunningRecognizeMetadata",
    "progressPercent": 100,
    "startTime": "2017-07-20T16:36:55.033650Z",
    "lastUpdateTime": "2017-07-20T16:37:17.158630Z"
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.speech.v1.LongRunningRecognizeResponse",
    "results": [
      {
        "alternatives": [
          {
            "transcript": "how old is the Brooklyn Bridge",
            "confidence": 0.96096134,
          }
        ]
      },
      {
        "alternatives": [
          {
            ...
          }
        ]
      }
    ]
  }
}

如果作業尚未完成,您可以重複發出 GET 要求來輪詢端點,直到回應的 done 屬性為 true 為止。

gcloud

如需完整的詳細資訊,請參閱 recognize-long-running 指令。

如要執行非同步語音辨識,請使用 Google Cloud CLI,提供本機檔案路徑或 Google Cloud Storage 網址。

gcloud ml speech recognize-long-running \
    'gs://cloud-samples-tests/speech/brooklyn.flac' \
     --language-code='en-US' --async

如果要求成功,伺服器會傳回 JSON 格式長時間執行作業的 ID。

{
  "name": OPERATION_ID
}

然後您可以執行下列指令,取得關於作業的資訊。

gcloud ml speech operations describe OPERATION_ID

您也可以執行下列指令來對作業進行輪詢,直到作業完成為止。

gcloud ml speech operations wait OPERATION_ID

作業完成後,作業會以 JSON 格式傳回音訊的轉錄內容。

{
  "@type": "type.googleapis.com/google.cloud.speech.v1.LongRunningRecognizeResponse",
  "results": [
    {
      "alternatives": [
        {
          "confidence": 0.9840146,
          "transcript": "how old is the Brooklyn Bridge"
        }
      ]
    }
  ]
}

Go

如要瞭解如何安裝及使用 Speech-to-Text 的用戶端程式庫,請參閱 Speech-to-Text 用戶端程式庫。詳情請參閱 Speech-to-Text Go API 參考說明文件

如要向 Speech-to-Text 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


func sendGCS(w io.Writer, client *speech.Client, gcsURI string) error {
	ctx := context.Background()

	// Send the contents of the audio file with the encoding and
	// and sample rate information to be transcripted.
	req := &speechpb.LongRunningRecognizeRequest{
		Config: &speechpb.RecognitionConfig{
			Encoding:        speechpb.RecognitionConfig_LINEAR16,
			SampleRateHertz: 16000,
			LanguageCode:    "en-US",
		},
		Audio: &speechpb.RecognitionAudio{
			AudioSource: &speechpb.RecognitionAudio_Uri{Uri: gcsURI},
		},
	}

	op, err := client.LongRunningRecognize(ctx, req)
	if err != nil {
		return err
	}
	resp, err := op.Wait(ctx)
	if err != nil {
		return err
	}

	// Print the results.
	for _, result := range resp.Results {
		for _, alt := range result.Alternatives {
			fmt.Fprintf(w, "\"%v\" (confidence=%3f)\n", alt.Transcript, alt.Confidence)
		}
	}
	return nil
}

Java

如要瞭解如何安裝及使用 Speech-to-Text 的用戶端程式庫,請參閱 Speech-to-Text 用戶端程式庫。詳情請參閱 Speech-to-Text Java API 參考說明文件

如要向 Speech-to-Text 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

/**
 * Performs non-blocking speech recognition on remote FLAC file and prints the transcription.
 *
 * @param gcsUri the path to the remote LINEAR16 audio file to transcribe.
 */
public static void asyncRecognizeGcs(String gcsUri) throws Exception {
  // Configure polling algorithm
  SpeechSettings.Builder speechSettings = SpeechSettings.newBuilder();
  TimedRetryAlgorithm timedRetryAlgorithm =
      OperationTimedPollAlgorithm.create(
          RetrySettings.newBuilder()
              .setInitialRetryDelay(Duration.ofMillis(500L))
              .setRetryDelayMultiplier(1.5)
              .setMaxRetryDelay(Duration.ofMillis(5000L))
              .setInitialRpcTimeout(Duration.ZERO) // ignored
              .setRpcTimeoutMultiplier(1.0) // ignored
              .setMaxRpcTimeout(Duration.ZERO) // ignored
              .setTotalTimeout(Duration.ofHours(24L)) // set polling timeout to 24 hours
              .build());
  speechSettings.longRunningRecognizeOperationSettings().setPollingAlgorithm(timedRetryAlgorithm);

  // Instantiates a client with GOOGLE_APPLICATION_CREDENTIALS
  try (SpeechClient speech = SpeechClient.create(speechSettings.build())) {

    // Configure remote file request for FLAC
    RecognitionConfig config =
        RecognitionConfig.newBuilder()
            .setEncoding(AudioEncoding.FLAC)
            .setLanguageCode("en-US")
            .setSampleRateHertz(16000)
            .build();
    RecognitionAudio audio = RecognitionAudio.newBuilder().setUri(gcsUri).build();

    // Use non-blocking call for getting file transcription
    OperationFuture<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response =
        speech.longRunningRecognizeAsync(config, audio);
    while (!response.isDone()) {
      System.out.println("Waiting for response...");
      Thread.sleep(10000);
    }

    List<SpeechRecognitionResult> results = response.get().getResultsList();

    for (SpeechRecognitionResult result : results) {
      // There can be several alternative transcripts for a given chunk of speech. Just use the
      // first (most likely) one here.
      SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
      System.out.printf("Transcription: %s\n", alternative.getTranscript());
    }
  }
}

Node.js

如要瞭解如何安裝及使用 Speech-to-Text 的用戶端程式庫,請參閱 Speech-to-Text 用戶端程式庫。詳情請參閱 Speech-to-Text Node.js API 參考說明文件

如要向語音轉文字驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證機制」。

// Imports the Google Cloud client library
const speech = require('@google-cloud/speech');

// Creates a client
const client = new speech.SpeechClient();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const gcsUri = 'gs://my-bucket/audio.raw';
// const encoding = 'Encoding of the audio file, e.g. LINEAR16';
// const sampleRateHertz = 16000;
// const languageCode = 'BCP-47 language code, e.g. en-US';

const config = {
  encoding: encoding,
  sampleRateHertz: sampleRateHertz,
  languageCode: languageCode,
};

const audio = {
  uri: gcsUri,
};

const request = {
  config: config,
  audio: audio,
};

// Detects speech in the audio file. This creates a recognition job that you
// can wait for now, or get its result later.
const [operation] = await client.longRunningRecognize(request);
// Get a Promise representation of the final result of the job
const [response] = await operation.promise();
const transcription = response.results
  .map(result => result.alternatives[0].transcript)
  .join('\n');
console.log(`Transcription: ${transcription}`);

Python

如要瞭解如何安裝及使用 Speech-to-Text 的用戶端程式庫,請參閱 Speech-to-Text 用戶端程式庫。詳情請參閱 Speech-to-Text Python API 參考說明文件

如要向 Speech-to-Text 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

from google.cloud import speech


def transcribe_gcs(gcs_uri: str) -> str:
    """Asynchronously transcribes the audio file from Cloud Storage
    Args:
        gcs_uri: The Google Cloud Storage path to an audio file.
            E.g., "gs://storage-bucket/file.flac".
    Returns:
        The generated transcript from the audio file provided.
    """
    client = speech.SpeechClient()

    audio = speech.RecognitionAudio(uri=gcs_uri)
    config = speech.RecognitionConfig(
        encoding=speech.RecognitionConfig.AudioEncoding.FLAC,
        sample_rate_hertz=44100,
        language_code="en-US",
    )

    operation = client.long_running_recognize(config=config, audio=audio)

    print("Waiting for operation to complete...")
    response = operation.result(timeout=90)

    transcript_builder = []
    # Each result is for a consecutive portion of the audio. Iterate through
    # them to get the transcripts for the entire audio file.
    for result in response.results:
        # The first alternative is the most likely one for this portion.
        transcript_builder.append(f"\nTranscript: {result.alternatives[0].transcript}")
        transcript_builder.append(f"\nConfidence: {result.alternatives[0].confidence}")

    transcript = "".join(transcript_builder)
    print(transcript)

    return transcript

其他語言

C#:請按照用戶端程式庫頁面上的 C# 設定說明操作,然後參閱 .NET 的 Speech-to-Text 參考說明文件

PHP:請按照用戶端程式庫頁面上的 PHP 設定說明操作,然後參閱 PHP 的 Speech-to-Text 參考文件

Ruby:請按照用戶端程式庫頁面上的 Ruby 設定操作說明操作,然後參閱 Ruby 適用的 Speech-to-Text 參考文件

將轉錄結果上傳至 Cloud Storage 值區

語音轉文字支援將長時間辨識結果直接上傳至 Cloud Storage 值區。如果您使用 Cloud Storage 觸發條件實作這項功能,Cloud Storage 上傳作業就能觸發通知,呼叫 Cloud 函式,而不需要輪詢 Speech-to-Text 以取得辨識結果。

如要將結果上傳至 Cloud Storage 值區,請在長時間執行的辨識要求中提供選用的 TranscriptOutputConfig 輸出設定。

  message TranscriptOutputConfig {

    oneof output_type {
      // Specifies a Cloud Storage URI for the recognition results. Must be
      // specified in the format: `gs://bucket_name/object_name`
      string gcs_uri = 1;
    }
  }

通訊協定

如要瞭解完整的詳細資訊,請參閱 longrunningrecognize API 端點。

以下範例說明如何使用 curl 傳送 POST 要求,其中要求主體會指定 Cloud Storage 值區的路徑。結果會上傳至這個位置,並以 JSON 檔案的形式儲存 SpeechRecognitionResult

curl -X POST \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     --data "{
  'config': {...},
  'output_config': {
     'gcs_uri':'gs://bucket/result-output-path.json'
  },
  'audio': {
    'uri': 'gs://bucket/audio-path'
  }
}" "https://speech.googleapis.com/v1p1beta1/speech:longrunningrecognize"

LongRunningRecognizeResponse 包含上傳失敗的 Cloud Storage 值區路徑。如果上傳失敗,系統會傳回輸出錯誤。如果已存在同名的檔案,上傳作業會將結果寫入新檔案,並在檔案名稱後方加上時間戳記。

{
  ...
  "metadata": {
    ...
    "outputConfig": {...}
  },
  ...
  "response": {
    ...
    "results": [...],
    "outputConfig": {
      "gcs_uri":"gs://bucket/result-output-path"
    },
    "outputError": {...}
  }
}

歡迎試用

如果您未曾使用過 Google Cloud,歡迎建立帳戶,親自體驗實際使用 Speech-to-Text 的成效。新客戶可以獲得價值 $300 美元的免費抵免額,可用於執行、測試及部署工作負載。

試用 Speech-to-Text 免費版