O Media Translation traduz um arquivo de áudio ou stream de fala para texto de outro idioma. Nesta página, fornecemos exemplos de código que mostram como traduzir áudio de streaming para texto usando bibliotecas de cliente do Media Translation.
Criar o projeto
Antes de usar o Media Translation, você precisa configurar um projeto do Google Cloud e ativar a API Media Translation para esse projeto.
- 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.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Verifique se a cobrança está ativada para o seu projeto do Google Cloud.
-
Enable the Media Translation API.
-
Create a service account:
-
In the Google Cloud console, go to the Create service account page.
Go to Create service account - Select your project.
-
In the Service account name field, enter a name. The Google Cloud console fills in the Service account ID field based on this name.
In the Service account description field, enter a description. For example,
Service account for quickstart
. - Click Create and continue.
-
Grant the Project > Owner role to the service account.
To grant the role, find the Select a role list, then select Project > Owner.
- Click Continue.
-
Click Done to finish creating the service account.
Do not close your browser window. You will use it in the next step.
-
-
Create a service account key:
- In the Google Cloud console, click the email address for the service account that you created.
- Click Keys.
- Click Add key, and then click Create new key.
- Click Create. A JSON key file is downloaded to your computer.
- Click Close.
-
Set the environment variable
GOOGLE_APPLICATION_CREDENTIALS
to the path of the JSON file that contains your credentials. This variable applies only to your current shell session, so if you open a new session, set the variable again. - Install the Google Cloud CLI.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Verifique se a cobrança está ativada para o seu projeto do Google Cloud.
-
Enable the Media Translation API.
-
Create a service account:
-
In the Google Cloud console, go to the Create service account page.
Go to Create service account - Select your project.
-
In the Service account name field, enter a name. The Google Cloud console fills in the Service account ID field based on this name.
In the Service account description field, enter a description. For example,
Service account for quickstart
. - Click Create and continue.
-
Grant the Project > Owner role to the service account.
To grant the role, find the Select a role list, then select Project > Owner.
- Click Continue.
-
Click Done to finish creating the service account.
Do not close your browser window. You will use it in the next step.
-
-
Create a service account key:
- In the Google Cloud console, click the email address for the service account that you created.
- Click Keys.
- Click Add key, and then click Create new key.
- Click Create. A JSON key file is downloaded to your computer.
- Click Close.
-
Set the environment variable
GOOGLE_APPLICATION_CREDENTIALS
to the path of the JSON file that contains your credentials. This variable applies only to your current shell session, so if you open a new session, set the variable again. - Install the Google Cloud CLI.
-
To initialize the gcloud CLI, run the following command:
gcloud init
- Instale a biblioteca de cliente na linguagem de sua preferência.
Tradução de fala
Os exemplos de código abaixo mostram como traduzir a fala de um arquivo que contém até cinco minutos de áudio ou de um microfone ao vivo. Veja recomendações sobre como fornecer dados de fala para ter a melhor precisão no reconhecimento em Práticas recomendadas.
As principais etapas são as mesmas, independentemente da fonte de áudio:
Inicialize um cliente
SpeechTranslationServiceClient
e o use para enviar solicitações ao Media Translation.Você pode reutilizar o mesmo cliente para várias solicitações.
Crie um objeto de solicitação
StreamingTranslateSpeechConfig
que especifique como processar o áudio.O objeto
StreamingTranslateSpeechConfig
consiste em um objetoTranslateSpeechConfig
que fornece informações sobre o arquivo de áudio de origem e uma sinalizaçãosingle_utterance
que especifica se o Media Translation continua traduzindo quando o falante faz uma pausa.O objeto
TranslateSpeechConfig
fornece especificações técnicas da fonte de áudio (como codificação e taxa de amostragem), define os idiomas de origem e de destino da tradução (usando os códigos BCP-47) e indica qual modelo de tradução a Media Translation usará na transcrição.Envie uma sequência de objetos de solicitação
StreamingTranslateSpeechRequest
.Envie uma sequência de solicitações para cada arquivo de áudio que você quer traduzir. A primeira solicitação fornece o objeto
StreamingTranslateSpeechConfig
para a solicitação, e as solicitações seguintes fornecem o conteúdo de áudio em streaming.Receba o objeto de resposta
StreamingTranslateSpeechResult
.Embora qualquer resposta com o valor
false
paratext_translation_result.is_final
seja recebida, o resultado traduzido mais recente substituirá o resultado anterior.Quando a Media Translation tiver um resultado final, o campo
text_translation_result.is_final
será definido comotrue
e qualquer resultado de tradução recebido posteriormente será anexado ao resultado anterior. Nessa instância, o resultado anterior não é substituído. É possível produzir a tradução concluída e começar com uma nova seção para a próxima parte da transcrição e do áudio correspondente.Quando o orador parar de falar, se o campo
single_utterance
estiver definido como "true" no objeto de solicitaçãoStreamingTranslateSpeechConfig
, a Media Translation retornará um eventoEND_OF_SINGLE_UTTERANCE
paraspeech_event_type
na resposta. O cliente deixará de enviar solicitações, mas continuará a receber respostas até a conclusão da tradução.O streaming tem um limite de 5 minutos. Se esse limite for excedido, o erro OUT_OF_RANGE será retornado.
Amostras de código
Como traduzir fala de um arquivo de áudio
Java
Para saber como instalar e usar a biblioteca de cliente da Media Translation, consulte Bibliotecas de cliente da Media Translation. Para mais informações, consulte a documentação de referência da API Media Translation em Java.
Para autenticar no Media Translation, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.
Node.js
Para saber como instalar e usar a biblioteca de cliente da Media Translation, consulte Bibliotecas de cliente da Media Translation. Para mais informações, consulte a documentação de referência da API Media Translation em Node.js.
Para autenticar no Media Translation, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.
Python
Para saber como instalar e usar a biblioteca de cliente da Media Translation, consulte Bibliotecas de cliente da Media Translation. Para mais informações, consulte a documentação de referência da API Media Translation em Python.
Para autenticar no Media Translation, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.
Como traduzir fala de um microfone
Java
Para saber como instalar e usar a biblioteca de cliente da Media Translation, consulte Bibliotecas de cliente da Media Translation. Para mais informações, consulte a documentação de referência da API Media Translation em Java.
Para autenticar no Media Translation, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.
Node.js
Para saber como instalar e usar a biblioteca de cliente da Media Translation, consulte Bibliotecas de cliente da Media Translation. Para mais informações, consulte a documentação de referência da API Media Translation em Node.js.
Para autenticar no Media Translation, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.
Python
Para saber como instalar e usar a biblioteca de cliente da Media Translation, consulte Bibliotecas de cliente da Media Translation. Para mais informações, consulte a documentação de referência da API Media Translation em Python.
Para autenticar no Media Translation, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.