音頻播放器採用的AVPlayer ,在程式啟動的時候需要配置AudioSession,AudioSession負責應用音訊設定,比如支不支援後台,打斷等等,這一步很重要,比如在viewdidload裡初始化AVplayer以後要調用下面的函數:
- (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;
}
}