I made an application that can speak a word (TTS) in the background.
But the player will be stopped after receiving this notice of interruption.
AVSpeechSynthesizer Audio interruption notification: {
AVAudioSessionInterruptionTypeKey = 1;
AVAudioSessionInterruptionWasSuspendedKey = 1;
}
After I found the solution here, which is shown below, adding a notification and implementing the following code.
However, I found that it AVAudioSessionInterruptionTypeEndedwould never appear. Even I laid the foundation for a function AVAudioSessionInterruptionTypeBeganthat still doesn't work.
My question is: how do I keep the AVSpeechSynthesizer running after receiving an interrupt notification?
[[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) {
[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];
});
}
}
source
share