Синхронный перевод
Запускайте длительную сессию устного перевода и получайте исходный и переведённый текст по мере обработки, необязательное TTS-аудио, события и итоговый отчёт.
Жизненный цикл SimultaneousInterpretationEventType, используемый onEvent, описан в разделе «События AI-сессий».
Жизненный цикл сессии перевода
Согласуйте запуск поставщика, активный источник аудио, упорядоченные потоковые результаты, обработку прерываний и окончательную остановку.
Предварительные условия
AIBudsAISDKинициализирован, зарегистрированный поставщик выбран и авторизован.- Поставщик поддерживает
SimultaneousInterpretationServiceAPI. - Идентификаторы исходного и целевого языков записаны через дефис и различаются.
- Если внутренняя запись AIBuds AI SDK отключена, приложение передаёт внешний PCM. Если источником служит подключённое устройство, оно соответствует
DeviceAudioRecordingAPI.
Реализация с помощью AI
Реализуйте этот сценарий с AI
Используйте официальный навык «Реализация синхронного перевода AIBuds» и адаптируйте сценарий к приложению.
Прочитайте и выполните инструкции https://docs-aibuds.github.io/ru/skills/implement-aibuds-simultaneous-interpretation. Используйте этот навык, чтобы реализовать «Реализация синхронного перевода AIBuds» в данном iOS-проекте и проверить результат.API Reference
Framework
AIBudsAI.xcframework
Import
- Swift
- Objective-C
import AIBuds
import AIBudsAI
import AIBudsAIFoundation#import <AIBuds/AIBuds-Swift.h>
#import <AIBudsAI/AIBudsAI-Swift.h>Declaration
- Swift
- Objective-C
/// Starts a simultaneous interpretation session.
/// - Parameters:
/// - config: The session configuration.
/// - onStartSuccess: Called with the started session.
/// - onStartFailure: Called when the session cannot start.
/// - onStopByInterruption: Called when an interruption stops the session.
/// - onException: Called for a recoverable session exception. The app decides
/// whether the session should stop.
/// - streamResultHandler: Called with incremental interpretation results.
/// - onEvent: Called for session-level events.
/// - onFinish: Called with the optional final report.
public static func startSimultaneousInterpretation(_ config: SimultaneousInterpretationConfig = .default,
onStartSuccess: ((_ session: SimultaneousInterpretationSessionConvertible) -> Void)? = nil,
onStartFailure: ((_ error: NSError) -> Void)? = nil,
onStopByInterruption: ((_ error: NSError?) -> Void)? = nil,
onException: ((_ error: NSError) -> Void)? = nil,
streamResultHandler: ((
_ isFinal: Bool,
_ response: SimultaneousInterpretationDataModel?,
_ error: Error?
) -> Void)? = nil,
onEvent: ((_ event: SimultaneousInterpretationEventModel) -> Void)? = nil,
onFinish: ((_ report: SimultaneousInterpretationReportModel?) -> Void)? = nil)
/// Stops the current simultaneous interpretation session.
public static func stopSimultaneousInterpretation()/// Starts a simultaneous interpretation session.
/// - Parameters:
/// - config: The session configuration.
/// - onStartSuccess: Called with the started session.
/// - onStartFailure: Called when the session cannot start.
/// - onStopByInterruption: Called when an interruption stops the session.
/// - onException: Called for a recoverable session exception.
/// - streamResultHandler: Called with incremental interpretation results.
/// - onEvent: Called for session-level events.
/// - onFinish: Called with the optional final report.
+ (void)startSimultaneousInterpretationWithConfig:(AIBudsSimultaneousInterpretationConfig * _Nonnull)config
onStartSuccess:(void (^ _Nullable)(id <AIBudsSimultaneousInterpretationSessionConvertible> _Nonnull))onStartSuccess
onStartFailure:(void (^ _Nullable)(NSError * _Nonnull))onStartFailure
onStopByInterruption:(void (^ _Nullable)(NSError * _Nullable))onStopByInterruption
onException:(void (^ _Nullable)(NSError * _Nonnull))onException
streamResultHandler:(void (^ _Nullable)(BOOL, AIBudsSimultaneousInterpretationDataModel * _Nullable, NSError * _Nullable))streamResultHandler
onEvent:(void (^ _Nullable)(AIBudsSimultaneousInterpretationEventModel * _Nonnull))onEvent
onFinish:(void (^ _Nullable)(AIBudsSimultaneousInterpretationReportModel * _Nullable))onFinish;
/// Stops the current simultaneous interpretation session.
+ (void)stopSimultaneousInterpretation;См. startSimultaneousInterpretation и stopSimultaneousInterpretation.
Конфигурация
SimultaneousInterpretationConfig предоставляет:
| Свойство | По умолчанию | Описание |
|---|---|---|
sourceLanguage | Язык приложения | Необязательный исходный язык; пустая строка включает автоопределение. |
targetLanguage | en-US | Обязательный целевой язык. |
enableTTS | true | Нужно ли синтезировать переведённую речь. |
enableVoicePlayback | true | Включено ли воспроизведение синтезированной речи. |
usesInternalAudioRecording | true | Записывает ли AIBuds AI SDK аудио для этой сессии. |
preferSpeakerOutput | false | Предпочитать ли вывод через динамик. |
Когда usesInternalAudioRecording равно false, AIBuds AI SDK не записывает аудио сессии. Приложение должно сохранить возвращённую сессию и передавать внешний PCM через appendInt16PCM(_:isFinal:) или appendAudioPCMBuffer(_:isFinal:).
Примеры использования
- Swift
- Objective-C
let config = SimultaneousInterpretationConfig.default
config.sourceLanguage = "zh-CN"
config.targetLanguage = "en-US"
config.usesInternalAudioRecording = true
config.preferSpeakerOutput = false
AIBudsAISDK.startSimultaneousInterpretation(
config,
onStartSuccess: { session in
currentSession = session
},
onStartFailure: { error in
print("Unable to start: \(error.localizedDescription)")
},
onStopByInterruption: { error in
print(error?.localizedDescription ?? "Session interrupted")
currentSession = nil
},
onException: { error in
print("Session exception: \(error.localizedDescription)")
},
streamResultHandler: { isFinal, response, error in
if let error {
print(error.localizedDescription)
return
}
guard let response else { return }
if response.isSourceTextDefinite {
print("Source: \(response.sourceText ?? "")")
}
if response.isTargetTextDefinite {
print("Target: \(response.targetText ?? "")")
}
if isFinal { print("Final result") }
},
onEvent: { event in
print(event)
},
onFinish: { report in
currentSession = nil
print(report ?? "No report")
}
)AIBudsSimultaneousInterpretationConfig *config =
[AIBudsSimultaneousInterpretationConfig defaultConfig];
config.sourceLanguage = @"zh-CN";
config.targetLanguage = @"en-US";
config.usesInternalAudioRecording = YES;
config.preferSpeakerOutput = NO;
[AIBudsAISDK startSimultaneousInterpretationWithConfig:config
onStartSuccess:^(id<AIBudsSimultaneousInterpretationSessionConvertible> session) {
self.currentSession = session;
}
onStartFailure:^(NSError *error) {
NSLog(@"Unable to start: %@", error.localizedDescription);
}
onStopByInterruption:^(NSError *error) {
NSLog(@"%@", error.localizedDescription ?: @"Session interrupted");
self.currentSession = nil;
}
onException:^(NSError *error) {
NSLog(@"Session exception: %@", error.localizedDescription);
}
streamResultHandler:^(
BOOL isFinal, AIBudsSimultaneousInterpretationDataModel *response, NSError *error) {
if (error != nil) {
NSLog(@"%@", error.localizedDescription);
return;
}
if (response.isSourceTextDefinite) {
NSLog(@"Source: %@", response.sourceText ?: @"");
}
if (response.isTargetTextDefinite) {
NSLog(@"Target: %@", response.targetText ?: @"");
}
}
onEvent:^(AIBudsSimultaneousInterpretationEventModel *event) {
NSLog(@"%@", event);
}
onFinish:^(AIBudsSimultaneousInterpretationReportModel *report) {
self.currentSession = nil;
NSLog(@"%@", report);
}];Когда session.isRecordingInternally равно false, внешним аудиоканалом управляет приложение. После onStartSuccess Demo запускает AI-запись на устройстве, передаёт каждый декодированный пакет PCM в session.appendInt16PCM(_:isFinal:), сначала останавливает запись устройства, а затем вызывает AIBudsAISDK.stopSimultaneousInterpretation().
Примечания
- Сохраняйте возвращённый при запуске
SimultaneousInterpretationSessionConvertible, чтобы отслеживать активную сессию и режим записи. onExceptionне обязательно останавливает сессию. Решите, продолжать работу или вызватьstopSimultaneousInterpretation().- Упорядочивайте подтверждённые сегменты по
sourceTextSequenceиtargetTextSequence, а не добавляйте безусловно каждый потоковый callback. - TTS-аудио в
SimultaneousInterpretationDataModelможет быть представлено относительным путём, полным путём или PCM-данными Base64.