クライアント ライブラリを使用して音声を文字に変換する

このページでは、Google Cloud クライアント ライブラリを用いて、お好みのプログラミング言語で Speech-to-Text に音声認識リクエスト送信する方法について説明します。

Speech-to-Text を使用すると、Google の音声認識技術をデベロッパーのアプリケーションに簡単に統合できます。音声データを Speech-to-Text API に送信し、音声ファイルの音声が文字に変換されたテキストを取得できます。サービスの詳細については、Speech-to-Text の基本をご覧ください。

始める前に

  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. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  3. Google Cloud プロジェクトで課金が有効になっていることを確認します

  4. Speech-to-Text API を有効にします。

    API を有効にする

  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 colunn 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. [新しいプリンシパル] フィールドに、ユーザー ID を入力します。 これは通常、Google アカウントのメールアドレスです。

    5. [ロールを選択] リストでロールを選択します。
    6. 追加のロールを付与するには、 [別のロールを追加] をクリックして各ロールを追加します。
    7. [保存] をクリックします。
    8. Install the Google Cloud CLI.
    9. To initialize the gcloud CLI, run the following command:

      gcloud init
    10. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

      プロジェクト セレクタに移動

    11. Google Cloud プロジェクトで課金が有効になっていることを確認します

    12. Speech-to-Text API を有効にします。

      API を有効にする

    13. 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 colunn 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. [新しいプリンシパル] フィールドに、ユーザー ID を入力します。 これは通常、Google アカウントのメールアドレスです。

      5. [ロールを選択] リストでロールを選択します。
      6. 追加のロールを付与するには、 [別のロールを追加] をクリックして各ロールを追加します。
      7. [保存] をクリックします。
      8. Install the Google Cloud CLI.
      9. To initialize the gcloud CLI, run the following command:

        gcloud init
      10. クライアント ライブラリは、アプリケーションのデフォルト認証情報を使用することによって、Google API で簡単に認証を行い、これらの API にリクエストを送信できます。アプリケーションのデフォルト認証情報を使用すると、ベースとなるコードを変更することなく、ローカルでのアプリケーションのテストやアプリケーションのデプロイが可能です。詳しくは、<atrack-type="commonincludes" l10n-attrs-original-order="href,track-type,track-name" l10n-encrypted-href="WDE63JFVMK0YqIWBqG8nCycgwkRfOeEqRvzYs1N+2tJUEhcZvE5VtDH5LoWw0lj/" track-name="referenceLink">クライアント ライブラリを使用して認証する</atrack-type="commonincludes">をご覧ください。

      11. Create local authentication credentials for your user account:

        gcloud auth application-default login

      また、クライアント ライブラリがインストールされていることを確認してください。

      音声文字変換をリクエストする

      次のコードを使用して、Speech-to-Text API に Recognize リクエストを送信します。

      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

      from google.cloud.speech_v2 import SpeechClient
      from google.cloud.speech_v2.types import cloud_speech
      
      def quickstart_v2(
          project_id: str,
          audio_file: str,
      ) -> cloud_speech.RecognizeResponse:
          """Transcribe an audio file."""
          # Instantiates a client
          client = SpeechClient()
      
          # Reads a file as bytes
          with open(audio_file, "rb") as f:
              content = f.read()
      
          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=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. 作成した認証情報を取り消して、ローカル認証情報ファイルを削除します。

        gcloud auth application-default revoke
      2. (省略可)gcloud CLI から認証情報を取り消します。

        gcloud auth revoke

      コンソール

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

      Go to Manage resources

    15. In the project list, select the project that you want to delete, and then click Delete.
    16. In the dialog, type the project ID, and then click Shut down to delete the project.
    17. gcloud

      Delete a Google Cloud project:

      gcloud projects delete PROJECT_ID

      次のステップ