收到音频中断通知后,AVSpeechSynthesizer停止

时间:2017-07-15 18:08:15

标签: ios objective-c avspeechsynthesizer

我制作了一个可以在背景中说出单词(TTS)的应用程序。

但是在收到此中断通知后,播放器将停止播放。

AVSpeechSynthesizer Audio interruption notification: {
    AVAudioSessionInterruptionTypeKey = 1;
    AVAudioSessionInterruptionWasSuspendedKey = 1; 
}

我在下面显示的解决方案后,添加通知并实现以下代码。

但是,我发现AVAudioSessionInterruptionTypeEnded永远不会出现。即使我将启动功能放在AVAudioSessionInterruptionTypeBegan中仍然无效。

我的问题是,如何在收到中断通知后让我的AVSpeechSynthesizer工作?

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAudioSessionInterruption:) name:AVAudioSessionInterruptionNotification object:aSession];

- (void)handleAudioSessionInterruption:(NSNotification*)notification {

    NSNumber *interruptionType = [[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey];
    NSNumber *interruptionOption = [[notification userInfo] objectForKey:AVAudioSessionInterruptionOptionKey];

    switch (interruptionType.unsignedIntegerValue) {
        case AVAudioSessionInterruptionTypeBegan:{
            [self interruptHandler];
            [self playObject];
        } break;
        case AVAudioSessionInterruptionTypeEnded:{
            if (interruptionOption.unsignedIntegerValue == AVAudioSessionInterruptionOptionShouldResume) {
                // Here you should continue playback.
                [self playObject];
            }
        } break;
        default:
            break;
    }
}

- (void) interruptHandler {
    @synchronized (self) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSError *error;
            AVAudioSession *aSession = [AVAudioSession sharedInstance];
            [aSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker error:&error];
            [aSession setMode:AVAudioSessionModeDefault error:&error];
            [aSession setActive: YES error: &error];
        });
    }
}

0 个答案:

没有答案