iOS後臺持續播放音樂 中斷後持續播放


-(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];
    //其中的_bgTaskId是後臺任務UIBackgroundTaskIdentifier _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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章