From 59435f8749afe0cd2dd32bdd373a5c8e76ca2c8f Mon Sep 17 00:00:00 2001 From: WenhaiLin Date: Fri, 29 May 2015 21:41:54 +0800 Subject: [PATCH] AudioEngine:Fixed audio can not resume if it is interrupted cause by an incoming phone call. --- cocos/audio/apple/AudioEngine-inl.mm | 29 ++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/cocos/audio/apple/AudioEngine-inl.mm b/cocos/audio/apple/AudioEngine-inl.mm index 60e18b7d44..01b4c9260b 100644 --- a/cocos/audio/apple/AudioEngine-inl.mm +++ b/cocos/audio/apple/AudioEngine-inl.mm @@ -162,6 +162,7 @@ void AudioEngineInterruptionListenerCallback(void* user_data, UInt32 interruptio { if ([[[UIDevice currentDevice] systemVersion] intValue] > 5) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:UIApplicationDidBecomeActiveNotification object:[AVAudioSession sharedInstance]]; } else { AudioSessionInitialize(NULL, NULL, AudioEngineInterruptionListenerCallback, self); @@ -172,6 +173,8 @@ void AudioEngineInterruptionListenerCallback(void* user_data, UInt32 interruptio -(void)handleInterruption:(NSNotification*)notification { + static bool resumeOnBecomingActive = false; + if ([notification.name isEqualToString:AVAudioSessionInterruptionNotification]) { NSInteger reason = [[[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey] integerValue]; if (reason == AVAudioSessionInterruptionTypeBegan) { @@ -179,17 +182,35 @@ void AudioEngineInterruptionListenerCallback(void* user_data, UInt32 interruptio } if (reason == AVAudioSessionInterruptionTypeEnded) { - OSStatus result = AudioSessionSetActive(true); - if (result) NSLog(@"Error setting audio session active! %d\n", result); - - alcMakeContextCurrent(s_ALContext); + if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) { + NSError *error = nil; + [[AVAudioSession sharedInstance] setActive:YES error:&error]; + alcMakeContextCurrent(s_ALContext); + } else { + resumeOnBecomingActive = true; + } } } + + if ([notification.name isEqualToString:UIApplicationDidBecomeActiveNotification] && resumeOnBecomingActive) { + resumeOnBecomingActive = false; + NSError *error = nil; + BOOL success = [[AVAudioSession sharedInstance] + setCategory: AVAudioSessionCategoryAmbient + error: &error]; + if (!success) { + printf("Fail to set audio session.\n"); + return; + } + [[AVAudioSession sharedInstance] setActive:YES error:&error]; + alcMakeContextCurrent(s_ALContext); + } } -(void) dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionInterruptionNotification object:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil]; [super dealloc]; }