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:
getSupportedLanguages
, which queries the supported languages for translation.translateMessage
, which translates the received text message after it is received.languages
in msgConfig
, 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 getSupportedLanguages
to query the supported languages for translation first:
conn.getSupportedLanguages().then(res => console.log(res))
When the recipient receives a text message, call translateMessage
to translate the message:
conn.translateMessage('hello', ['zh']).then(res => console.log(res))
When creating a text message, the sender enables automatic translation by setting languages
in msgConfig
as the target language for translation. The SDK sends both the original message and the translated message.
// Send the message.
let option = {
chatType: 'singleChat',
type: 'txt',
to: 'userId',
msg: 'hello',
msgConfig:{ languages: ['zh'] } // Set the target language for translation.
}
let msg = WebIM.message.create(option);
conn.send(msg)
// Occurs when the message is received.
conn.addEventHandler('MESSAGE', {
onTextMessage: (message) => {
console.log('message', message.translations)
}
})