Transcribir voz a texto mediante la línea de comandos

En esta página se explica cómo enviar una solicitud de reconocimiento de voz a Speech-to-Text mediante la interfaz REST y el comando curl.

Speech-to-Text permite integrar de forma sencilla las tecnologías de reconocimiento de voz de Google en las aplicaciones de desarrolladores. Puedes enviar datos de audio a la API Speech-to-Text, que devuelve una transcripción de texto de ese archivo de audio. Para obtener más información sobre el servicio, consulta el artículo Conceptos básicos de Speech-to-Text.

Antes de empezar

  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.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Speech-to-Text APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    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.

      Ir a IAM
    2. Selecciona el proyecto.
    3. Haz clic en Conceder acceso.
    4. En el campo Nuevos principales, introduce tu identificador de usuario. Normalmente, se trata de la dirección de correo de una cuenta de Google.

    5. En la lista Selecciona un rol, elige un rol.
    6. Para conceder más roles, haz clic en Añadir otro rol y añade cada rol adicional.
    7. Haz clic en Guardar.
  6. Install the Google Cloud CLI.

  7. Si utilizas un proveedor de identidades (IdP) externo, primero debes iniciar sesión en la CLI de gcloud con tu identidad federada.

  8. Para inicializar gcloud CLI, ejecuta el siguiente comando:

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

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  10. Verify that billing is enabled for your Google Cloud project.

  11. Enable the Speech-to-Text APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    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.

      Ir a IAM
    2. Selecciona el proyecto.
    3. Haz clic en Conceder acceso.
    4. En el campo Nuevos principales, introduce tu identificador de usuario. Normalmente, se trata de la dirección de correo de una cuenta de Google.

    5. En la lista Selecciona un rol, elige un rol.
    6. Para conceder más roles, haz clic en Añadir otro rol y añade cada rol adicional.
    7. Haz clic en Guardar.
  13. Install the Google Cloud CLI.

  14. Si utilizas un proveedor de identidades (IdP) externo, primero debes iniciar sesión en la CLI de gcloud con tu identidad federada.

  15. Para inicializar gcloud CLI, ejecuta el siguiente comando:

    gcloud init
  16. Hacer una solicitud de transcripción de audio

    Usa el siguiente código de ejemplo para enviar una solicitud REST recognize a la API Speech-to-Text.

    1. Ejecuta este comando para crear un archivo JSON como entrada de la solicitud. Sustituye /full/path/to/audio/file.wav por la ruta al archivo de audio que quieras transcribir:

      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. Usa curl para hacer una solicitud 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

      Deberías ver una respuesta similar a la siguiente:

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

    Has enviado tu primera solicitud a Speech-to-Text.

    Limpieza

    Para evitar que se apliquen cargos en tu cuenta de Google Cloud por los recursos utilizados en esta página, sigue estos pasos.

    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. Siguientes pasos