您可以使用 ML Kit 在不同語言之間翻譯文字。ML Kit 可在 50 多種語言之間進行翻譯。
立即試用
- 請試用範例應用程式,瞭解這個 API 的使用範例。
事前準備
- 在專案層級的
build.gradle
檔案中,請務必在buildscript
和allprojects
區段中納入 Google 的 Maven 存放區。 - 將 ML Kit Android 程式庫的依附元件新增至模組的應用程式層級 Gradle 檔案,通常為
app/build.gradle
:dependencies { // ... implementation 'com.google.mlkit:translate:17.0.3' }
翻譯文字字串
如要將字串翻譯成其他語言:
建立
Translator
物件,並使用原文和目標語言進行設定:Kotlin
// Create an English-German translator: val options = TranslatorOptions.Builder() .setSourceLanguage(TranslateLanguage.ENGLISH) .setTargetLanguage(TranslateLanguage.GERMAN) .build() val englishGermanTranslator = Translation.getClient(options)
Java
// Create an English-German translator: TranslatorOptions options = new TranslatorOptions.Builder() .setSourceLanguage(TranslateLanguage.ENGLISH) .setTargetLanguage(TranslateLanguage.GERMAN) .build(); final Translator englishGermanTranslator = Translation.getClient(options);
如果您不清楚輸入文字的語言,可以使用 Language Identification API,這個 API 會提供語言標記。然後使用
TranslateLanguage.fromLanguageTag()
將標記轉換為TranslateLanguage
。避免在裝置上同時保留太多語言模型。
確認已將必要的翻譯模型下載到裝置。請等到您知道模型可用時,再呼叫
translate()
。Kotlin
var conditions = DownloadConditions.Builder() .requireWifi() .build() englishGermanTranslator.downloadModelIfNeeded(conditions) .addOnSuccessListener { // Model downloaded successfully. Okay to start translating. // (Set a flag, unhide the translation UI, etc.) } .addOnFailureListener { exception -> // Model couldn’t be downloaded or other internal error. // ... }
Java
DownloadConditions conditions = new DownloadConditions.Builder() .requireWifi() .build(); englishGermanTranslator.downloadModelIfNeeded(conditions) .addOnSuccessListener( new OnSuccessListener
() { @Override public void onSuccess(Void v) { // Model downloaded successfully. Okay to start translating. // (Set a flag, unhide the translation UI, etc.) } }) .addOnFailureListener( new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Model couldn’t be downloaded or other internal error. // ... } }); 語言模型約為 30 MB,因此請勿下載不必要的語言模型,並且只在使用者指定的情況下透過 Wi-Fi 下載語言模型。您也應刪除不需要的模型。請參閱「明確管理翻譯模型」。
確認已下載模型後,請將來源語言的文字字串傳遞至
translate()
:Kotlin
englishGermanTranslator.translate(text) .addOnSuccessListener { translatedText -> // Translation successful. } .addOnFailureListener { exception -> // Error. // ... }
Java
englishGermanTranslator.translate(text) .addOnSuccessListener( new OnSuccessListener
() { @Override public void onSuccess(@NonNull String translatedText) { // Translation successful. } }) .addOnFailureListener( new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Error. // ... } }); 系統會將翻譯文字 (以您設定的目標語言顯示) 傳遞至成功事件監聽器。
請確認在
Translator
物件不再使用時,系統會呼叫close()
方法。如果您在 Fragment 或 AppCompatActivity 中使用 Translator,可以透過簡單的方式執行這項操作,方法是在 Fragment 或 AppCompatActivity 上呼叫 LifecycleOwner.getLifecycle(),然後呼叫 Lifecycle.addObserver。例如:
Kotlin
val options = ... val translator = Translation.getClient(options) getLifecycle().addObserver(translator)
Java
TranslatorOptions options = ... Translator translator = Translation.getClient(options); getLifecycle().addObserver(translator); ... use translator ...
請注意,這項操作假設程式碼位於實作 LifecycleOwner 的類別中 (例如 Fragment 或 AppCompatActivity)。
明確管理轉譯模型
當您按照上述方式使用翻譯 API 時,ML Kit 會根據需求,自動將特定語言的翻譯模型下載到裝置。您也可以使用 ML Kit 的翻譯模型管理 API,明確管理裝置上要使用的翻譯模型。如果您想提前下載模型,或從裝置中刪除不需要的模型,這項功能就很實用。
Kotlin
val modelManager = RemoteModelManager.getInstance() // Get translation models stored on the device. modelManager.getDownloadedModels(TranslateRemoteModel::class.java) .addOnSuccessListener { models -> // ... } .addOnFailureListener { // Error. } // Delete the German model if it's on the device. val germanModel = TranslateRemoteModel.Builder(TranslateLanguage.GERMAN).build() modelManager.deleteDownloadedModel(germanModel) .addOnSuccessListener { // Model deleted. } .addOnFailureListener { // Error. } // Download the French model. val frenchModel = TranslateRemoteModel.Builder(TranslateLanguage.FRENCH).build() val conditions = DownloadConditions.Builder() .requireWifi() .build() modelManager.download(frenchModel, conditions) .addOnSuccessListener { // Model downloaded. } .addOnFailureListener { // Error. }
Java
RemoteModelManager modelManager = RemoteModelManager.getInstance(); // Get translation models stored on the device. modelManager.getDownloadedModels(TranslateRemoteModel.class) .addOnSuccessListener(new OnSuccessListener<Set>() { @Override public void onSuccess(Set models) { // ... } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Error. } }); // Delete the German model if it's on the device. TranslateRemoteModel germanModel = new TranslateRemoteModel.Builder(TranslateLanguage.GERMAN).build(); modelManager.deleteDownloadedModel(germanModel) .addOnSuccessListener(new OnSuccessListener () { @Override public void onSuccess(Void v) { // Model deleted. } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Error. } }); // Download the French model. TranslateRemoteModel frenchModel = new TranslateRemoteModel.Builder(TranslateLanguage.FRENCH).build(); DownloadConditions conditions = new DownloadConditions.Builder() .requireWifi() .build(); modelManager.download(frenchModel, conditions) .addOnSuccessListener(new OnSuccessListener () { @Override public void onSuccess(Void v) { // Model downloaded. } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Error. } });