在NSArray中按顺序运行TTS(Text-to-Speech)可以使用循环和异步操作来实现。以下是一个示例解决方案:
NSArray *textArray = @[@"Hello", @"World", @"This", @"is", @"TTS"];
- (void)runTTSForTextArray:(NSArray *)textArray atIndex:(NSInteger)index {
if (index >= textArray.count) {
// 所有文本已经转换完成
return;
}
// 获取当前索引位置的文本
NSString *text = textArray[index];
// 创建AVSpeechUtterance对象,设置文本和语音设置
AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:text];
AVSpeechSynthesizer *synthesizer = [[AVSpeechSynthesizer alloc] init];
// 异步运行TTS
[synthesizer speakUtterance:utterance];
// 当TTS完成后,递归调用方法来继续下一个文本的转换
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(utterance.preUtteranceDelay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self runTTSForTextArray:textArray atIndex:index+1];
});
}
[self runTTSForTextArray:textArray atIndex:0];
这样,每个文本将按顺序进行TTS转换,并且每个转换都将在上一个转换完成后异步执行。