视频后台播放

1. 修改 Info.plist

在 Info.plist 中添加 Required background modes ,并在下面添加一项 App plays audio or streams audio/video using AirPlay

2. 修改 Capabilities

在 Capabilities 中开启 Background Modes    勾选

视频后台播放_第1张图片

3. 修改 AppDelegate

在 AppDelegate 的 application: didFinishLaunchingWithOptions: 方法中,添加以下代码:1234// 告诉app支持后台播放AVAudioSession *audioSession = [AVAudioSession sharedInstance];[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];[audioSession setActive:YES error:nil];


二、后台播放视频


1. 退到后台时移除 playerLayer 上的 player在 viewController 中添加退到后台监听:

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];[center addObserver:self selector:@selector(removePlayerOnPlayerLayer) name:UIApplicationDidEnterBackgroundNotification object:nil];

移除 player :

- (void)removePlayerOnPlayerLayer { _playerLayer.player = nil;}

2. 回到前台时重新添加 player在 viewController 中添加回到前台监听:

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];[center addObserver:self selector:@selector(resetPlayerToPlayerLayer) name:UIApplicationWillEnterForegroundNotification object:nil];

重新添加 player :

- (void)resetPlayerToPlayerLayer { _playerLayer.player = _player;}


二、自定义控制台


#pragma mark - 锁屏界面信息相关

- (void)updateLockScreen

{

    NSMutableDictionary *songDict = [NSMutableDictionary dictionary];


    // 音频名字

    [songDict setObject:@"她来听我的演唱会"  forKey:MPMediaItemPropertyTitle];


    // 歌手

    [songDict setObject:@"张学友"  forKey:MPMediaItemPropertyArtist];


    // 歌曲的总时间

    [songDict setObject:@(200) forKeyedSubscript:MPMediaItemPropertyPlaybackDuration];


    // 当前时间

    [songDict setObject:@(30) forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];


    // 播放速率

    [songDict setObject:@(1.0) forKey:MPNowPlayingInfoPropertyPlaybackRate];


    // 锁屏音频封面

    MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:@"Yosemite00.jpg"]];

    [songDict setObject:artwork forKey:MPMediaItemPropertyArtwork];


    // 设置控制中心歌曲信息

    [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songDict];


    if (@available(iOS 11.0, *)) {

        //判断是不是iOS 11 //根据当前播放器的播放状态显示控制器中心的播放状态

              [MPNowPlayingInfoCenter defaultCenter].playbackState = MPNowPlayingPlaybackStatePaused;


    }

}

你可能感兴趣的:(视频后台播放)