iOS AVFAudio之AVSpeechSynthesizer

357 阅读1分钟

AVSpeechSynthesizer是iOS库中文字转语音的对象,可以后台播报声音

1、遵守代理协议

<AVSpeechSynthesizerDelegate>

2、实例化一个 AVSpeechSynthesizer 对象

@property (nonatomic, strong) AVSpeechSynthesizer *speechSynthesizer;
@property (nonatomic, strong) NSMutableArray *broadCastList;
@property (nonatomic, assign) NSUInteger currentSpeechIndex;


self.speechSynthesizer = [[AVSpeechSynthesizer alloc] init];
self.speechSynthesizer.delegate = self;

3、播报方法:

- (void)broadcastSpeech {
    // speechSynthesizer 不是在播放状态 且有数据需要播放
    if (![self.speechSynthesizer isSpeaking]) {
        if (self.broadCastList.count&& (self.broadCastList.count - 1 >= self.currentSpeechIndex))) {
              // 实例化AVSpeechUtterance对象
            AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:self.broadCastList[self.currentSpeechIndex]];
             // 播报
            [self.speechSynthesizer speakUtterance:utterance];
        } else {
            [self.broadCastList removeAllObjects];
        }
    } else {
    
        [self.speechSynthesizer continueSpeaking];
    }
}

4、代理事件AVSpeechSynthesizerDelegate

//开始播报
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didStartSpeechUtterance:(AVSpeechUtterance *)utterance;
// 结束播报
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance {
self.currentSpeechIndex++;
[self broadcastSpeech];
}
//停止播报
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didPauseSpeechUtterance:(AVSpeechUtterance *)utterance;
//取消播报
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didCancelSpeechUtterance:(AVSpeechUtterance *)utterance {
    if ([self.speechSynthesizer isSpeaking]) {
        [self.speechSynthesizer continueSpeaking];
     } else {
         [self broadcastSpeech];
     }
 }

4、后台播报有可能被中断,需要添加中断通知AVAudioSessionInterruptionNotification

 [[NSNotificationCenter defaultCenter] addObserver:self selector: @selector(handleInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];

处理通知事件:

- (void)handleInterruption:(NSNotification*)notification {
    if ([[notification.userInfo valueForKey:AVAudioSessionInterruptionTypeKey] integerValue] == 1) {
        if (![self.speechSynthesizer isSpeaking]) {
            return;
        }
        [self.speechSynthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryImmediate];
    } else {
        if ([self.speechSynthesizer isSpeaking]) {
        [self.speechSynthesizer continueSpeaking];
        } else {
            [self broadcastSpeech];
        }
     }
  }