iOS AVPlayer 后台播放问题自动停止问题 防止应用被后台挂起方法

1、创建播放器时创建AVAudioSession

AVAudioSession *session = [AVAudioSessionsharedInstance];
[session setCategory:AVAudioSessionCategoryPlaybackerror:nil];
[session setActive:YES error:nil];

2、在plist文件中添加字段

Required background modes

在这里添加后台播放:

App plays audio or streams audio/video using AirPlay

3、在设备将要挂起app时添加下面代码

- (void)applicationWillResignActive:(UIApplication *)application {
    
    if ([MediaPlayerplayer].playStatus == MediaPlayerPlayStatusPlaying) {
        UIDevice* device = [UIDevicecurrentDevice];
        if ([devicerespondsToSelector:@selector(isMultitaskingSupported)]) {
            if(device.multitaskingSupported) {
                if(device.multitaskingSupported) {
                    if ([MediaPlayerplayer].bgTaskId ==UIBackgroundTaskInvalid) {
                        [MediaPlayerplayer].bgTaskId = [[UIApplicationsharedApplication]beginBackgroundTaskWithExpirationHandler:NULL];
                    }
                }
            }
        }
    }
}

在设备进入前台时添加下面代码

if ([MediaPlayerplayer].bgTaskId !=UIBackgroundTaskInvalid) {
        [[UIApplicationsharedApplication]endBackgroundTask:[MediaPlayerplayer].bgTaskId];
        [MediaPlayerplayer].bgTaskId =UIBackgroundTaskInvalid;
    }

使用这三步基本可以保证在后台的长时间播放问题,且不会因为后台挂起APP导致的播放停止问题。


你可能感兴趣的:(iOS,开发笔记)