iOS 后台播放音乐问题记录

1.首先需要将Background Modes开启并选择Audio,

iOS 后台播放音乐问题记录


2.在controller中注册后台播放下一首/暂停/前一首的远程监听, 并在viewDidLoad里     [self becomeFirstResponder];

#pragma mark - 远程控制事件监听
- (BOOL)canBecomeFirstResponder{
    return YES;
}

- (void)remoteControlReceivedWithEvent:(UIEvent *)event{
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlPlay:
        case UIEventSubtypeRemoteControlPause:
            [[FYPlayManager sharedInstance] pauseMusic];
            break;
           
        case UIEventSubtypeRemoteControlNextTrack:
            [[FYPlayManager sharedInstance] nextMusic];
            break;
           
        case UIEventSubtypeRemoteControlPreviousTrack:
            [[FYPlayManager sharedInstance] previousMusic];
           
        default:
            break;
    }
}

3.后台播放网络音乐时加载过长会导致app被悬挂,在AppDelegate解决方案如下:

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;

}

- (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];

}