前言
需要實現像鬧鐘那樣通知過后然后不進入app直接播放音樂的功能
持續后臺播放,網絡歌曲也可以,重點是持續播放,后臺播放很簡單,但是后臺持續播放,則需要做一些處理,申請后臺id,才能實現持續播放。
實現方式
1.開啟后臺模式
開啟音樂后臺.png
2.在Appdelegate.m的applicationWillResignActive:方法中激活后臺播放
UIBackgroundTaskIdentifier _bgTaskId;
-(void)applicationWillResignActive:(UIApplication *)application
{
//開啟后臺處理多媒體事件
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
AVAudioSession *session=[AVAudioSession sharedInstance];
[session setActive:YES error:nil];
//后臺播放
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
//這樣做,可以在按home鍵進入后臺后 ,播放一段時間,幾分鐘吧。但是不能持續播放網絡歌曲,若需要持續播放網絡歌曲,還需要申請后臺任務id,具體做法是:
_bgTaskId=[AppDelegate backgroundPlayerID:_bgTaskId];
}
//實現一下backgroundPlayerID:這個方法:
+(UIBackgroundTaskIdentifier)backgroundPlayerID:(UIBackgroundTaskIdentifier)backTaskId
{
//設置并激活音頻會話類別
AVAudioSession *session=[AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
[session setActive:YES error:nil];
//允許應用程序接收遠程控制
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
//設置后臺任務ID
UIBackgroundTaskIdentifier newTaskId=UIBackgroundTaskInvalid;
newTaskId=[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
if(newTaskId!=UIBackgroundTaskInvalid&&backTaskId!=UIBackgroundTaskInvalid)
{
[[UIApplication sharedApplication] endBackgroundTask:backTaskId];
}
return newTaskId;
}
3.處理中斷事件,如電話,微信語音等。
原理是,在音樂播放被中斷時,暫停播放,在中斷完成后,開始播放
//處理中斷事件的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterreption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
-->實現接收到中斷通知時的方法
//處理中斷事件
-(void)handleInterreption:(NSNotification *)sender
{
if(_played)
{
[self.playView.player pause];
_played=NO;
}
else
{
[self.playView.player play];
_played=YES;
}
}
繼續研究,上面主要實現了音樂在app中開啟播放然后推到后臺繼續播放,而我的需求是通知來到之后進行音樂的啟動播放
參考鏈接
http://www.lxweimin.com/p/ab300ea6e90c
補充
1.發現鬧鐘的原理并不是后臺播放音樂,而是到了一個時間發出一個通知,這個通知每分鐘重復一次,然后播放自定義通知音樂,需要在30s以內
2.如果是處理得比較好的,進入app界面內再次響鈴然后程序退到后臺掉用后臺持續播放音樂
3.例子:火箭鬧鐘