Transcreva voz em texto através da linha de comandos

Esta página mostra como enviar um pedido de reconhecimento de voz para o Speech-to-Text usando a interface REST e o comando curl.

A conversão de voz em texto permite a integração fácil das tecnologias de reconhecimento de voz da Google nas aplicações dos programadores. Pode enviar dados de áudio para a API Speech-to-Text, que devolve uma transcrição de texto desse ficheiro de áudio. Para mais informações acerca do serviço, consulte o artigo Noções básicas de conversão de voz em texto.

Antes de começar

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

      Aceder ao IAM
    2. Selecione o projeto.
    3. Clique em Conceder acesso.
    4. No campo Novos responsáveis, introduza o identificador do utilizador. Normalmente, este é o endereço de email de uma Conta Google.

    5. Na lista Selecionar uma função, selecione uma função.
    6. Para conceder funções adicionais, clique em Adicionar outra função e adicione cada função adicional.
    7. Clique em Guardar.
  6. Install the Google Cloud CLI.

  7. Se estiver a usar um fornecedor de identidade (IdP) externo, primeiro, tem de iniciar sessão na CLI gcloud com a sua identidade federada.

  8. Para inicializar a CLI gcloud, execute o seguinte comando:

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

      Aceder ao IAM
    2. Selecione o projeto.
    3. Clique em Conceder acesso.
    4. No campo Novos responsáveis, introduza o identificador do utilizador. Normalmente, este é o endereço de email de uma Conta Google.

    5. Na lista Selecionar uma função, selecione uma função.
    6. Para conceder funções adicionais, clique em Adicionar outra função e adicione cada função adicional.
    7. Clique em Guardar.
  13. Install the Google Cloud CLI.

  14. Se estiver a usar um fornecedor de identidade (IdP) externo, primeiro, tem de iniciar sessão na CLI gcloud com a sua identidade federada.

  15. Para inicializar a CLI gcloud, execute o seguinte comando:

    gcloud init
  16. Faça um pedido de transcrição de áudio

    Use o seguinte exemplo de código para enviar um pedido REST recognize para a API Speech-to-Text.

    1. Execute este comando para criar um ficheiro JSON como entrada para o pedido. Substitua /full/path/to/audio/file.wav pelo caminho para o ficheiro de áudio que quer transcrever:

      echo "{
        \"config\": {
          \"auto_decoding_config\": {},
          \"language_codes\": [\"en-US\"],
          \"model\": \"long\"
        },
        \"content\": \"$(base64 -w 0 /full/path/to/audio/file.wav | sed 's/+/-/g; s/\//_/g')\"
      }" > /tmp/data.txt
    2. Use curl para fazer um pedido recognize:

      curl -X POST -H "Content-Type: application/json; charset=utf-8" \
          -H "Authorization: Bearer $(gcloud auth print-access-token)" \
          -d @/tmp/data.txt \
          https://speech.googleapis.com/v2/projects/PROJECT_ID/locations/global/recognizers/_:recognize

      Deve ver uma resposta semelhante à seguinte:

        {
          "results": [
            {
              "alternatives": [
                {
                  "transcript": "how old is the Brooklyn Bridge",
                  "confidence": 0.98267895
                }
              ]
            }
          ]
        }
      

    Enviou o seu primeiro pedido ao Speech-to-Text.

    Limpar

    Para evitar incorrer em cobranças na sua Google Cloud conta pelos recursos usados nesta página, siga estes passos.

    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

    Consola

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

    Go to Manage resources

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

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

    Go to Manage resources

  22. In the project list, select the project that you want to delete, and then click Delete.
  23. In the dialog, type the project ID, and then click Shut down to delete the project.
  24. O que se segue?