[英]Resuming an app running in background after a phone call ios
我有一個ios應用程序,當它移動到后台時繼續播放音樂。 現在,如果有電話,無論是否應答,應用程序都不會恢復播放音樂。 這兩天我一直在讀這個問題的帖子。他們中沒有人解決了我的問題。
我正在使用AVQueuePlayer對象,因為我在需要時也流式播放音樂。 現在,自ios6以來,委托方法已被棄用。 所以我正在使用Notications。
令人驚訝的是,中斷結束(電話結束)被通知,播放音樂的代碼也被寫入,但應用程序jus不會播放音樂,直到它來到前景(與另一個通知)
這是我的代碼
-(void)viewWillAppear
{.....
........
.....
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioInterruptionNotification:) name:AVAudioSessionInterruptionNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioInterruptionNotification:) name:UIApplicationDidBecomeActiveNotification object:nil]
}
-(void)audioInterruptionNotification:(NSNotification *) aNotification {
NSLog(@"Interrupt %@", aNotification);
NSDictionary *dict = [aNotification userInfo];
NSUInteger typeKey = [[dict objectForKey:@"AVAudioSessionInterruptionTypeKey"] unsignedIntegerValue]; NSLog(@"%d", typeKey);
if (typeKey == 0)
{
[avPlayer play];
NSLog(@"1.......");
}
else if (typeKey == 1)
{
[avPlayer play];
NSLog(@"3...............");
;
}
}
此外,我嘗試通過調度隊列引發延遲。 委托方法似乎不起作用。 但是,通過蘋果恢復通話后,gaana,saavn和官方音樂應用程序恢復。 所以這是可能的。 我似乎錯過了一些東西。 如果我使用核心電話。我將不得不添加一個整個框架,這將增加應用程序的大小。 如果這是唯一的方法。請告訴我們如何。
謝謝。我非常感謝你的時間。
所以我過了一會兒就回來了,我看到我的問題仍然沒有答案。 好吧,我已經解決了我的問題。 事實證明這只是一個缺失的簡單陳述。
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
以及我在我的問題中寫的代碼。
我已經解決了問題 - 應用程序被電話打斷了,音樂消失了怎么樣?
OSStatus result1 = AudioSessionInitialize(NULL, NULL, interruptionListener, NULL);
實現interruptionListener
:
void interruptionListener( void * inClientData, UInt32 inInterruptionState){ if (inInterruptionState == kAudioSessionBeginInterruption) { NSLog(@"Begin kAudioSessionBeginInterruption"); alcMakeContextCurrent(NULL); // important } else if (inInterruptionState == kAudioSessionEndInterruption) { AVAudioSession * audioSession = [AVAudioSession sharedInstance]; NSError * err = nil; [audioSession setCategory :AVAudioSessionCategoryPlayback error:&err]; // important if(err){ NSLog(@"audioSession: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]); return; } err = nil; [audioSession setActive:YES error:&err]; if(err){ NSLog(@"audioSession: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]); return; } //AudioSessionSetActive(true); //sometimes have no effect // use alcMakeContextCurrent to set the context——with the context you stored before // important NSLog(@"End kAudioSessionEndInterruption"); } }
現在,當時鍾或電話中斷,音樂可以播放時,它是可以的。
但是如果你接聽電話然后觸摸'HOME'(沒有掛斷電話),然后回去掛機,然后回到應用程序,音樂無法播放,你應該這樣做:
當應用程序從后台轉到前台時,請設置AVAudioSession
和context
。 (不只是在中斷結束時設置它們)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.