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;

}

}


+ Recent posts