iOS 后台播放音乐问题记录

来源:互联网 发布:fedora linux镜像下载 编辑:程序博客网 时间:2024/06/02 02:43

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



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

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

- (void)remoteControlReceivedWithEvent:(UIEvent *)event{
   switch (event.subtype) {
       caseUIEventSubtypeRemoteControlPlay:
       caseUIEventSubtypeRemoteControlPause:
            [[FYPlayManagersharedInstance]pauseMusic];
           break;
           
       caseUIEventSubtypeRemoteControlNextTrack:
            [[FYPlayManagersharedInstance]nextMusic];
           break;
           
       caseUIEventSubtypeRemoteControlPreviousTrack:
            [[FYPlayManagersharedInstance]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) {

        [[UIApplicationsharedApplication] endBackgroundTask:backTaskId];

    }

    return newTaskId;

}

- (void)applicationWillResignActive:(UIApplication *)application {

    //开启后台处理多媒体事件

    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

    AVAudioSession *session=[AVAudioSessionsharedInstance];

    [session setActive:YESerror:nil];

    //后台播放

    [session setCategory:AVAudioSessionCategoryPlaybackerror:nil];

    //这样做,可以在按home键进入后台后,播放一段时间,几分钟吧。但是不能持续播放网络歌曲,若需要持续播放网络歌曲,还需要申请后台任务id,具体做法是:

    _bgTaskId=[AppDelegatebackgroundPlayerID:_bgTaskId];

}