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