在 Android 上使用 ML Kit 翻譯文字

你可以使用 ML Kit 翻譯不同語言的文字。ML Kit 可以翻譯超過 50 種語言

馬上試試

事前準備

  1. 在專案層級的 build.gradle 檔案中,請務必在 buildscriptallprojects 區段中納入 Google 的 Maven 存放區。
  2. 將 ML Kit Android 程式庫的依附元件新增至模組的應用程式層級的 Gradle 檔案,通常為 app/build.gradle
    dependencies {
      // ...
    
      implementation 'com.google.mlkit:translate:17.0.2'
    }
    

翻譯一段文字

如何在兩種語言之間翻譯字串:

  1. 建立 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,以取得語言標記。然後使用 TranslateLanguage.fromLanguageTag() 將標記轉換為 TranslateLanguage

    請避免同時在裝置上保留過多語言模型,

  2. 確認所需翻譯模型已下載到裝置。 確認模型可用前,請勿呼叫 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 下載這些模型。建議您一併刪除不需要的模型。請參閱「明確管理翻譯模型」。

  3. 確認已下載模型後,請將原文語言的字串傳送至 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.
                // ...
              }
            });

    系統會以您設定的目標語言將翻譯完成的文字傳遞至成功事件監聽器。

  4. 確認不再使用 Translator 物件時,系統會呼叫 close() 方法。

    如果您在 Fragment 或 AppCompatActivity 中使用譯者,最簡單的做法是在 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>() {
        @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.
        }
    });