1. App plist에 정보 추가하기
- Required background modes (Array) > item0 : App plays audio
2. AVAudioSession에 등록하기
- (void)beginBackgroundTaskAndRemoteControl
{
NSLog(@"<--------------------");
NSError * error = nil;
// 오디오 세션을 음악 재생에 사용함을 선언
BOOL state = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
if(state == NO){
NSLog(@"Error MusicPlayer : %@", error);
return;
}
[[AVAudioSession sharedInstance] setActive: YES error: nil];
// 백그라운드 작업 갱신
self.prevTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
NSLog(@"begin taskId : %u", self.prevTaskId);
// 리모컨 이벤트 받도록 선언
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
3. 완료 후 백그라운드 작업 및 리모컨 이벤트 해제
- (void)endBackgroundTaskAndRemoteControl
{
// 리모컨 이벤트 해제
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
NSLog(@"end taskId : %u", self.prevTaskId);
// 기존 작업 종료
if (self.prevTaskId != UIBackgroundTaskInvalid)
{
[[UIApplication sharedApplication] endBackgroundTask:self.prevTaskId];
}
self.prevTaskId = UIBackgroundTaskInvalid;
}
4. 리모콘 이벤트에 대한 처리 메소드 추가
- (void)remoteControlReceivedWithEvent:(UIEvent *)event
{
NSLog(@"remoteControlReceived!!");
// 리모컨 이벤트가 아닌 경우
if(event.type != UIEventTypeRemoteControl)
return;
// 리모컨 이벤트에 따른 동작들
switch (event.subtype)
{
case UIEventSubtypeRemoteControlTogglePlayPause:
if(self.mediaPlayer.playbackState == MPMoviePlaybackStatePlaying){
[self.mediaPlayer pause];
} else {
[self.mediaPlayer play];
}
break;
case UIEventSubtypeRemoteControlStop:
[self.mediaPlayer stop];
break;
case UIEventSubtypeRemoteControlNextTrack:
[self playNext];
break;
case UIEventSubtypeRemoteControlPreviousTrack:
[self playPrev];
break;
default:
break;
}
}
'iOS' 카테고리의 다른 글
UICollectionView setCollectionViewLayout Crash (0) | 2014.03.13 |
---|---|
UICollectionView 사용 (0) | 2014.03.13 |
MPMoviePlayerController에서 풀스크린으로 사용하기 (0) | 2013.06.04 |
UIWebView에서 alert, confirm 자바스크립트 처리하기 (0) | 2013.03.25 |
ios에서 ttf폰트 사용하기 (0) | 2012.10.22 |