ストリーミング入力の音声を文字に変換する

このセクションでは、マイクからの入力などのストリーミング音声をテキストに変換する方法について説明します。

ストリーミング音声認識では、音声を Speech-to-Text にストリーミングし、音声を処理しながらリアルタイムでストリーム音声認識の結果を受信できます。ストリーミング音声認識リクエストについては、音声の制限もご覧ください。ストリーミング音声認識は、gRPC 経由でのみ利用できます。

始める前に

  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

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

      ローカル ファイルでストリーミング音声認識を実行する

      ローカル音声ファイルに対して、ストリーミング音声認識を実行する例を次に示します。ストリームのリクエストで送信される音声には 25 KB の上限があります。この上限は、最初の StreamingRecognize リクエストと、ストリーム内の各メッセージのサイズの両方に適用されます。この上限を超えると、エラーがスローされます。

      Python

      from google.cloud.speech_v2 import SpeechClient
      from google.cloud.speech_v2.types import cloud_speech as cloud_speech_types
      
      def transcribe_streaming_v2(
          project_id: str,
          audio_file: str,
      ) -> cloud_speech_types.StreamingRecognizeResponse:
          """Transcribes audio from audio file stream.
      
          Args:
              project_id: The GCP project ID.
              audio_file: The path to the audio file to transcribe.
      
          Returns:
              The response from the transcribe method.
          """
          # Instantiates a client
          client = SpeechClient()
      
          # Reads a file as bytes
          with open(audio_file, "rb") as f:
              content = f.read()
      
          # In practice, stream should be a generator yielding chunks of audio data
          chunk_length = len(content) // 5
          stream = [
              content[start : start + chunk_length]
              for start in range(0, len(content), chunk_length)
          ]
          audio_requests = (
              cloud_speech_types.StreamingRecognizeRequest(audio=audio) for audio in stream
          )
      
          recognition_config = cloud_speech_types.RecognitionConfig(
              auto_decoding_config=cloud_speech_types.AutoDetectDecodingConfig(),
              language_codes=["en-US"],
              model="long",
          )
          streaming_config = cloud_speech_types.StreamingRecognitionConfig(
              config=recognition_config
          )
          config_request = cloud_speech_types.StreamingRecognizeRequest(
              recognizer=f"projects/{project_id}/locations/global/recognizers/_",
              streaming_config=streaming_config,
          )
      
          def requests(config: cloud_speech_types.RecognitionConfig, audio: list) -> list:
              yield config
              yield from audio
      
          # Transcribes the audio into text
          responses_iterator = client.streaming_recognize(
              requests=requests(config_request, audio_requests)
          )
          responses = []
          for response in responses_iterator:
              responses.append(response)
              for result in response.results:
                  print(f"Transcript: {result.alternatives[0].transcript}")
      
          return responses
      
      

      ローカルの音声ファイルを Speech-to-Text API にストリーミングすることは可能ですが、同期音声認識を実行することをおすすめします。

      クリーンアップ

      このページで使用したリソースについて、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

      次のステップ