Translation is a popular feature widely used in real-time chat apps. To enable translation, the Agora Chat SDK has integrated the Microsoft Azure Translation API, which enables messages to be translated either when they are being sent or after they are received.
The SDK supports translation in the following use cases:
Before proceeding, ensure that your development environment meets the following requirements:
The Chat SDK provides the following methods for implementing translation functionalities:
fetchSupportedLanguages
, which queries the supported languages for translation.translateMessage
, which translates the text message after it is received.ChatTextMessageBody.targetLanguages
, which automatically translates the text message when it is being sent. When the recipient receives the message, it contains the message in both the original and target languages.This section introduces how to integrate translation functionalities into your project.
In both on-demand translation and automatic translation scenarios, call fetchSupportLanguages
to query the supported languages for translation first:
// Fetches the supported languages for translation.
try {
List<ChatTranslateLanguage> list =
await ChatClient.getInstance.chatManager.fetchSupportedLanguages();
} on ChatError catch (e) {
}
When the recipient receives a text message, call translateMessage
to translate the message:
// Specifies the target language for translation
List<String> languages = ["en"];
try {
// Translate the received text message, which is in `textMessage`
ChatMessage translatedMessage = await ChatClient.getInstance.chatManager
.translateMessage(msg: textMessage, languages: languages);
} on ChatError catch (e) {
}
When the translation finishes, the translated message is stored in the message. Get the translated message in ChatTextMessageBody.translations
:
ChatTextMessageBody body = translatedMessage.body as ChatTextMessageBody;
debugPrint("translation: ${body.translations}");
When creating a text message, the sender enables automatic translation by setting ChatTextMessageBody.targetLanguages
as the target language for translation:
// Specifies the target language for translation.
ChatMessage textMessage = ChatMessage.createTxtSendMessage(
username: targetUser,
content: content,
targetLanguages: ["en"],
);
The SDK sends both the original message and the translated message. After the recipient receives the message, call translation
to retrieve the translated message:
ChatTextMessageBody body = receiveMessage.body as ChatTextMessageBody;
debugPrint("translation: ${body.translations}");