跳到主要内容

AI 文本翻译

将文本从源语言翻译为目标语言,并增量接收译文。

前提条件

  • AIBudsAISDK 已初始化,并已选择注册的服务商。
  • 服务商支持 AITextTranslationServiceAPI
  • 输入文本和目标语言不为空。
  • 语言标识符使用 zh-CNen-US 等连字符格式;源语言为空时启用自动检测。

使用 AI 辅助实现

使用 AI 开发

让 AI 帮助实现此工作流

使用官方“实现 AIBuds 文本翻译”技能,根据你的 App 完成实现。

请阅读并遵循 https://docs-aibuds.github.io/zh-Hans/skills/implement-aibuds-text-translation,使用该技能在当前 iOS 项目中完成“实现 AIBuds 文本翻译”,并验证结果。
查看官方技能

API 参考

框架

AIBudsAI.xcframework

导入

Swift
import AIBudsAI

声明

Swift
/// Translates text from one language to another.
/// - Parameters:
///   - text: The text to translate.
///   - sourceLanguage: Source language code. An empty string enables auto-detect.
///   - targetLanguage: Target language code.
///   - streamResultHandler: Called repeatedly with translation results.
///     - isFinal: `true` when translation is complete.
///     - transcript: The current incremental translated text.
///     - error: The translation error, or `nil` on success.
public static func translateText(_ text: String,
                    from sourceLanguage: String,
                      to targetLanguage: String,
                    streamResultHandler: ((_ isFinal: Bool, _ transcript: String?, _ error: Error?) -> Void)? = nil)

/// Cancels the current text translation operation.
public static func cancelTextTranslation()

请参阅 translateTextcancelTextTranslation

使用示例

Swift
AIBudsAISDK.translateText(
    "你好,欢迎使用 AIBuds SDK。",
    from: "zh-CN",
    to: "en-US"
) { isFinal, transcript, error in
    DispatchQueue.main.async {
        if let error {
            translationLabel.text = error.localizedDescription
            return
        }

        if let transcript {
            translationLabel.text = transcript
        }

        translateButton.isEnabled = isFinal
    }
}

注意事项

  • 不要显式设置相同的源语言和目标语言。需要自动检测时使用空的源语言字符串。
  • transcript 为增量结果,可替换此前展示的结果。
  • 此 API 仅翻译文本。连续语音翻译请使用同声传译。
  • cancelTextTranslation() 没有完成回调;请求取消时应更新本地状态。