标签:
音频播放器采用的AVPlayer ,在程序启动的时候需要配置AudioSession,AudioSession负责应用音频的设置,比如支不支持后台,打断等等,这一步很重要,比如在viewdidload里初始化AVplayer以后要调用下面的函数:
/** 设置音频会话 */ //这种方式后台,可以连续播放非网络请求歌曲,遇到网络请求歌曲就废,需要后台申请task
-(void)setAudioSession{
AVAudioSession *audioSession=[AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
[audioSession setActive:YES error:nil];
}
除了代码的初始化,很重要的一步是对info-plist的设置,让应用支持音频的后台播放
库的引入包括:
AudioToolBox.framework
MediaPlayer.framework
CoreMedia.framework
AVFoundation.framework
在播放视图的ViewController里加上这两个函数:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[self resignFirstResponder];
}
当然也可以同理放到delegate.m里面的进入后台和回到前台的函数中,否则的话,上面的代码只是允许当前视图的情况下进入后台可以Remote控制
在AppDelegate里要申请后台任务来进行处理
- (void)applicationDidEnterBackground:(UIApplication *)application {
[application beginReceivingRemoteControlEvents];
}
在添加远程控制代码:
-(void)remoteControlReceivedWithEvent:(UIEvent *)event{
//if it is a remote control event handle it correctly
if (event.type == UIEventTypeRemoteControl) {
if (event.subtype == UIEventSubtypeRemoteControlPlay) {
[self playBarSelector:self.mPlayButton];
}if (event.subtype == UIEventSubtypeRemoteControlPause) {
[self playBarSelector:self.mPlayButton];
} else if (event.subtype == UIEventSubtypeRemoteControlNextTrack){
[self playBarSelector:self.mNextButton];
[self configNowPlayingInfoCenter];
}else if (event.subtype == UIEventSubtypeRemoteControlPreviousTrack){
[self playBarSelector:self.mUpwardButton];
[self configNowPlayingInfoCenter];
}
}
}
最后切换上一首和下一首要更新锁屏信息,重新调一下configNowPlayingInfoCenter方法
- (void)configNowPlayingInfoCenter {
if (NSClassFromString(@"MPNowPlayingInfoCenter")) {
// 1.播放信息中心
MPNowPlayingInfoCenter *center = [MPNowPlayingInfoCenter defaultCenter];
// 2.初始化播放信息
NSMutableDictionary *info = [NSMutableDictionary dictionary];
// 专辑名称
info[MPMediaItemPropertyAlbumTitle] = self.operatorObject.mExerciseText;
// 歌手
info[MPMediaItemPropertyArtist] = @"雅思听听小组";
// 歌曲名称
info[MPMediaItemPropertyTitle] = [NSString stringWithFormat:@"%@ - %@", self.operatorObject.mTextName, [self.operatorObject.mTitle substringToIndex:9]];
// 设置图片
info[MPMediaItemPropertyArtwork] = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:@"Default"]];
// 设置持续时间(歌曲的总时间)
info[MPMediaItemPropertyPlaybackDuration] = @(self.mAudioPlayerLong);
// 设置当前播放进度
info[MPNowPlayingInfoPropertyElapsedPlaybackTime] = @(self.mPlayerCurrentTime);
// 3.切换播放信息
center.nowPlayingInfo = info;
}
}
标签:
原文地址:http://www.cnblogs.com/Milo-CTO/p/4446919.html