클라이언트 라이브러리를 사용하여 음성을 텍스트로 변환하기

이 페이지에서는 Google Cloud 클라이언트 라이브러리를 사용하여 선호하는 프로그래밍 언어로 Speech-to-Text에 음성 인식 요청을 보내는 방법을 설명합니다.

Speech-to-Text를 사용하면 Google 음성 인식 기술을 개발자 애플리케이션에 간편하게 통합할 수 있습니다. 오디오 데이터를 Speech-to-Text API로 보내면 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. 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 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. 새 주 구성원 필드에 사용자 식별자를 입력합니다. 일반적으로 Google 계정의 이메일 주소입니다.

    5. 역할 선택 목록에서 역할을 선택합니다.
    6. 역할을 추가로 부여하려면 다른 역할 추가를 클릭하고 각 역할을 추가합니다.
    7. 저장을 클릭합니다.
    8. Install the Google Cloud CLI.
    9. To initialize the gcloud CLI, run the following command:

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

      Go to project selector

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

    12. Enable the Speech-to-Text APIs.

      Enable the APIs

    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. 새 주 구성원 필드에 사용자 식별자를 입력합니다. 일반적으로 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에 요청을 보낼 수 있습니다. 애플리케이션 기본 사용자 인증 정보를 사용하면 애플리케이션을 로컬에서 테스트하고 기본 코드를 변경하지 않은 상태로 배포할 수 있습니다. 자세한 내용은 클라이언트 라이브러리 사용을 위한 인증을 참고하세요.

      11. 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.

      또한 클라이언트 라이브러리를 설치했는지 확인합니다.

      오디오 텍스트 변환 요청하기

      Speech-to-Text API에 Recognize 요청을 보내려면 다음 코드를 사용하세요.

      자바

      // 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

      콘솔

    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

      다음 단계