使用用戶端程式庫將語音轉錄為文字

本頁面說明如何使用Google Cloud 用戶端程式庫,以您偏好的程式設計語言將語音辨識要求傳送至 Speech-to-Text。

Speech-to-Text 可讓您將 Google 語音辨識技術輕鬆整合至開發人員應用程式。您可將音訊資料傳送至 Speech-to-Text API,然後 API 會傳回該音訊檔案的文字轉錄結果。如要進一步瞭解這項服務,請參閱語音轉文字基本概念

事前準備

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Speech-to-Text APIs.

    Enable the APIs

  5. Make sure that you have the following role or roles on the project: Cloud Speech Administrator

    Check for the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. In the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.

    4. For all rows that specify or include you, check the Role column to see whether the list of roles includes the required roles.

    Grant the roles

    1. In the Google Cloud console, go to the IAM page.

      前往「IAM」頁面
    2. 選取專案。
    3. 按一下「授予存取權」
    4. 在「New principals」(新增主體) 欄位中,輸入您的使用者 ID。 這通常是 Google 帳戶的電子郵件地址。

    5. 在「Select a role」(選取角色) 清單中,選取角色。
    6. 如要授予其他角色,請按一下 「新增其他角色」,然後新增每個其他角色。
    7. 按一下 [Save]
  6. Install the Google Cloud CLI.

  7. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  8. To initialize the gcloud CLI, run the following command:

    gcloud init
  9. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  10. Make sure that billing is enabled for your Google Cloud project.

  11. Enable the Speech-to-Text APIs.

    Enable the APIs

  12. Make sure that you have the following role or roles on the project: Cloud Speech Administrator

    Check for the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. In the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.

    4. For all rows that specify or include you, check the Role column to see whether the list of roles includes the required roles.

    Grant the roles

    1. In the Google Cloud console, go to the IAM page.

      前往「IAM」頁面
    2. 選取專案。
    3. 按一下「授予存取權」
    4. 在「New principals」(新增主體) 欄位中,輸入您的使用者 ID。 這通常是 Google 帳戶的電子郵件地址。

    5. 在「Select a role」(選取角色) 清單中,選取角色。
    6. 如要授予其他角色,請按一下 「新增其他角色」,然後新增每個其他角色。
    7. 按一下 [Save]
  13. Install the Google Cloud CLI.

  14. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  15. To initialize the gcloud CLI, run the following command:

    gcloud init
  16. 用戶端程式庫可以使用應用程式預設憑證,輕鬆向 Google API 進行驗證,然後傳送要求給這些 API。使用應用程式預設憑證,您可以在本機測試及部署應用程式,不必變更基礎程式碼。詳情請參閱「 驗證以使用用戶端程式庫」。

  17. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

  18. 此外,請確認您已安裝用戶端程式庫

    提出音訊轉錄要求

    請使用下列程式碼,將 Recognize 要求傳送至 Speech-to-Text API。

    Java

    // Imports the Google Cloud client library
    import com.google.api.gax.longrunning.OperationFuture;
    import com.google.cloud.speech.v2.AutoDetectDecodingConfig;
    import com.google.cloud.speech.v2.CreateRecognizerRequest;
    import com.google.cloud.speech.v2.OperationMetadata;
    import com.google.cloud.speech.v2.RecognitionConfig;
    import com.google.cloud.speech.v2.RecognizeRequest;
    import com.google.cloud.speech.v2.RecognizeResponse;
    import com.google.cloud.speech.v2.Recognizer;
    import com.google.cloud.speech.v2.SpeechClient;
    import com.google.cloud.speech.v2.SpeechRecognitionAlternative;
    import com.google.cloud.speech.v2.SpeechRecognitionResult;
    import com.google.protobuf.ByteString;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.List;
    import java.util.concurrent.ExecutionException;
    
    public class QuickstartSampleV2 {
    
      public static void main(String[] args) throws IOException, ExecutionException,
          InterruptedException {
        String projectId = "my-project-id";
        String filePath = "path/to/audioFile.raw";
        String recognizerId = "my-recognizer-id";
        quickstartSampleV2(projectId, filePath, recognizerId);
      }
    
      public static void quickstartSampleV2(String projectId, String filePath, String recognizerId)
          throws IOException, ExecutionException, InterruptedException {
    
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests. After completing all of your requests, call
        // the "close" method on the client to safely clean up any remaining background resources.
        try (SpeechClient speechClient = SpeechClient.create()) {
          Path path = Paths.get(filePath);
          byte[] data = Files.readAllBytes(path);
          ByteString audioBytes = ByteString.copyFrom(data);
    
          String parent = String.format("projects/%s/locations/global", projectId);
    
          // First, create a recognizer
          Recognizer recognizer = Recognizer.newBuilder()
              .setModel("latest_long")
              .addLanguageCodes("en-US")
              .build();
    
          CreateRecognizerRequest createRecognizerRequest = CreateRecognizerRequest.newBuilder()
              .setParent(parent)
              .setRecognizerId(recognizerId)
              .setRecognizer(recognizer)
              .build();
    
          OperationFuture<Recognizer, OperationMetadata> operationFuture =
              speechClient.createRecognizerAsync(createRecognizerRequest);
          recognizer = operationFuture.get();
    
          // Next, create the transcription request
          RecognitionConfig recognitionConfig = RecognitionConfig.newBuilder()
              .setAutoDecodingConfig(AutoDetectDecodingConfig.newBuilder().build())
              .build();
    
          RecognizeRequest request = RecognizeRequest.newBuilder()
              .setConfig(recognitionConfig)
              .setRecognizer(recognizer.getName())
              .setContent(audioBytes)
              .build();
    
          RecognizeResponse response = speechClient.recognize(request);
          List<SpeechRecognitionResult> results = response.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.
            if (result.getAlternativesCount() > 0) {
              SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
              System.out.printf("Transcription: %s%n", alternative.getTranscript());
            }
          }
        }
      }
    }

    Python

    import os
    
    from google.cloud.speech_v2 import SpeechClient
    from google.cloud.speech_v2.types import cloud_speech
    
    PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")
    
    
    def quickstart_v2(audio_file: str) -> cloud_speech.RecognizeResponse:
        """Transcribe an audio file.
        Args:
            audio_file (str): Path to the local audio file to be transcribed.
        Returns:
            cloud_speech.RecognizeResponse: The response from the recognize request, containing
            the transcription results
        """
        # Reads a file as bytes
        with open(audio_file, "rb") as f:
            audio_content = f.read()
    
        # Instantiates a client
        client = SpeechClient()
    
        config = cloud_speech.RecognitionConfig(
            auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
            language_codes=["en-US"],
            model="long",
        )
    
        request = cloud_speech.RecognizeRequest(
            recognizer=f"projects/{PROJECT_ID}/locations/global/recognizers/_",
            config=config,
            content=audio_content,
        )
    
        # Transcribes the audio into text
        response = client.recognize(request=request)
    
        for result in response.results:
            print(f"Transcript: {result.alternatives[0].transcript}")
    
        return response
    
    

    您已將第一個要求傳送至 Speech-to-Text。

    清除所用資源

    如要避免系統向您的 Google Cloud 帳戶收取本頁所用資源的費用,請按照下列步驟操作。

    1. Optional: Revoke the authentication credentials that you created, and delete the local credential file.

      gcloud auth application-default revoke
    2. Optional: Revoke credentials from the gcloud CLI.

      gcloud auth revoke

    控制台

  19. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  20. In the project list, select the project that you want to delete, and then click Delete.
  21. In the dialog, type the project ID, and then click Shut down to delete the project.
  22. gcloud

    Delete a Google Cloud project:

    gcloud projects delete PROJECT_ID

    後續步驟