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導致的播放停止問題。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章