AI 文本翻译
将文本从源语言翻译为目标语言,并增量接收译文。
前提条件
AIBudsAISDK已初始化,并已选择注册的服务商。- 服务商支持
AITextTranslationServiceAPI。 - 输入文本和目标语言不为空。
- 语言标识符使用
zh-CN、en-US等连字符格式;源语言为空时启用自动检测。
使用 AI 辅助实现
使用 AI 开发
让 AI 帮助实现此工作流
使用官方“实现 AIBuds 文本翻译”技能,根据你的 App 完成实现。
请阅读并遵循 https://docs-aibuds.github.io/zh-Hans/skills/implement-aibuds-text-translation,使用该技能在当前 iOS 项目中完成“实现 AIBuds 文本翻译”,并验证结果。API 参考
框架
AIBudsAI.xcframework
导入
- Swift
- Objective-C
import AIBudsAI#import <AIBudsAI/AIBudsAI-Swift.h>声明
- Swift
- Objective-C
/// 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()/// 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: `YES` when translation is complete.
/// - transcript: The current incremental translated text.
/// - error: The translation error, or `nil` on success.
+ (void)translateText:(NSString * _Nonnull)text
from:(NSString * _Nonnull)sourceLanguage
to:(NSString * _Nonnull)targetLanguage
streamResultHandler:(void (^ _Nullable)(BOOL, NSString * _Nullable, NSError * _Nullable))streamResultHandler;
/// Cancels the current text translation operation.
+ (void)cancelTextTranslation;请参阅 translateText 和 cancelTextTranslation。
使用示例
- Swift
- Objective-C
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
}
}[AIBudsAISDK translateText:@"你好,欢迎使用 AIBuds SDK。"
from:@"zh-CN"
to:@"en-US"
streamResultHandler:^(BOOL isFinal, NSString *transcript, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (error != nil) {
self.translationLabel.text = error.localizedDescription;
return;
}
if (transcript != nil) {
self.translationLabel.text = transcript;
}
self.translateButton.enabled = isFinal;
});
}];注意事项
- 不要显式设置相同的源语言和目标语言。需要自动检测时使用空的源语言字符串。
- transcript 为增量结果,可替换此前展示的结果。
- 此 API 仅翻译文本。连续语音翻译请使用同声传译。
cancelTextTranslation()没有完成回调;请求取消时应更新本地状态。